/// <summary>
        /// 创建一个web browser 对象,并打开一个新的空白页
        /// </summary>
        private void CreateNewWebBrowser()
        {
            var autoSet = new AutoResetEvent(false);
          
            // Instruct CEF to not render to a window at all.
            CefWindowInfo cefWindowInfo = CefWindowInfo.Create();
            cefWindowInfo.SetAsWindowless(IntPtr.Zero, true);

            // Settings for the browser window itself (e.g. should JavaScript be enabled?).
            var cefBrowserSettings = new CefBrowserSettings();

            // Initialize some the cust interactions with the browser process.
            // The browser window will be 1280 x 720 (pixels).
            var cefClient = new HeadLessCefClient(1024, 720);
            var loader = cefClient.GetCurrentLoadHandler();
            loader.BrowserCreated += (s, e) =>
            {

                //事件通知 当cef  browser 创建完毕
                //创建完毕后 保存 browser 对象的实例
                this.WebBrowser = e.Browser;
                this._is_cef_browser_has_created = true;

                //发送终止信号
                autoSet.Set();
            };
            //注册  加载完毕事件handler
            loader.LoadEnd += this.OnWebBrowserLoadEnd;
            // Start up the browser instance.
            string url = "about:blank";
            CefBrowserHost.CreateBrowser(cefWindowInfo, cefClient, cefBrowserSettings, url);

            //等待结束信号
            autoSet.WaitOne();
        }
示例#2
0
        /// <summary>
        /// 加载Cef相关的资源
        /// </summary>
        public MainUIRender(GraphicsDevice gd, IntPtr handle, uint windwosWidth, uint windowsHeight)
        {
            _gd            = gd;
            _windowsHeight = windowsHeight;
            _windowsWidth  = windwosWidth;
            CefWindowInfo cefWindowInfo = CefWindowInfo.Create();

            cefWindowInfo.SetAsWindowless(handle, true);

            CefBrowserSettings cefBrowserSettings = new CefBrowserSettings()
            {
                BackgroundColor           = new CefColor(0, 60, 85, 115),
                JavaScript                = CefState.Enabled,
                JavaScriptAccessClipboard = CefState.Disabled,
                JavaScriptCloseWindows    = CefState.Disabled,
                JavaScriptDomPaste        = CefState.Disabled,
                //JavaScriptOpenWindows = CefState.Disabled,
                LocalStorage = CefState.Disabled
            };

            // Initialize some of the custom interactions with the browser process.
            this.cefClient = new CefOSRClient(this);

            // Start up the browser instance.
            CefBrowserHost.CreateBrowser(cefWindowInfo, this.cefClient, cefBrowserSettings, string.IsNullOrEmpty(this.url) ? "http://www.google.com" : this.url);
        }
        /// <summary>
        /// Initialization
        /// </summary>
        /// <param name="width">Browser rect width</param>
        /// <param name="height">Browser rect height</param>
        /// <param name="starturl"></param>
        public void Init(int width, int height, string starturl)
        {
            RegisterMessageRouter();

            CefWindowInfo cefWindowInfo = CefWindowInfo.Create();

            cefWindowInfo.SetAsWindowless(IntPtr.Zero, false);
            var cefBrowserSettings = new CefBrowserSettings {
                JavaScript          = CefState.Enabled,
                TabToLinks          = CefState.Enabled,
                WebSecurity         = CefState.Disabled,
                WebGL               = CefState.Enabled,
                WindowlessFrameRate = 30
            };



            _client = new WorkerCefClient(width, height, this);

            string url = "http://www.yandex.ru/";

            if (starturl != "")
            {
                url = starturl;
            }
            CefBrowserHost.CreateBrowser(cefWindowInfo, _client, cefBrowserSettings, url);



            _initialized = true;
        }
示例#4
0
        private void StartCef()
        {
#if UNITY_EDITOR
            CefRuntime.Load(Path.Combine(Application.dataPath, "Plugins", "Cef", "Windows"));
#else
            CefRuntime.Load();
#endif


            var cefMainArgs = new CefMainArgs(new string[] { });
            var cefApp      = new OffscreenCEFClient.OffscreenCEFApp();

            // This is where the code path diverges for child processes.
            if (CefRuntime.ExecuteProcess(cefMainArgs, cefApp, IntPtr.Zero) != -1)
            {
                Debug.LogError("Could not start the secondary process.");
            }

            var cefSettings = new CefSettings
            {
                //ExternalMessagePump = true,
                MultiThreadedMessageLoop = false,
                SingleProcess            = true,
                LogSeverity = CefLogSeverity.Verbose,
                LogFile     = "cef.log",
                WindowlessRenderingEnabled = true,
                NoSandbox = true
            };

            // Start the browser process (a child process).
            CefRuntime.Initialize(cefMainArgs, cefSettings, cefApp, IntPtr.Zero);

            // Instruct CEF to not render to a window.
            CefWindowInfo cefWindowInfo = CefWindowInfo.Create();
            cefWindowInfo.SetAsWindowless(IntPtr.Zero, true);

            // Settings for the browser window itself (e.g. enable JavaScript?).
            CefBrowserSettings cefBrowserSettings = new CefBrowserSettings()
            {
            };

            Debug.Log("Start with window: " + this.windowWidth + ", " + this.windowHeight);

            // Initialize some of the custom interactions with the browser process.
            this.cefClient = new OffscreenCEFClient(
                this.windowWidth,
                this.windowHeight,
                this.hideScrollbars,
                this.BrowserTexture,
                this
                );

            // Start up the browser instance.
            CefBrowserHost.CreateBrowser(cefWindowInfo, this.cefClient, cefBrowserSettings, string.IsNullOrEmpty(this.overlayUrl) ? "http://www.google.com" : this.overlayUrl);
        }
        private void StartCef()
        {
#if UNITY_EDITOR
            CefRuntime.Load("./Assets/Plugins/x86_64");
#else
            CefRuntime.Load();
#endif

            var cefMainArgs = new CefMainArgs(new string[] { });
            var cefApp      = new OffscreenCEFClient.OffscreenCEFApp();

            // This is where the code path diverges for child processes.
            if (CefRuntime.ExecuteProcess(cefMainArgs, cefApp, IntPtr.Zero) != -1)
            {
                Debug.LogError("Could not start the secondary process.");
            }

            var cefSettings = new CefSettings
            {
                //ExternalMessagePump = true,
                MultiThreadedMessageLoop = false,
                SingleProcess            = true,
                LogSeverity = CefLogSeverity.Verbose,
                LogFile     = "cef.log",
                WindowlessRenderingEnabled = true,
                NoSandbox = true,
            };

            // Start the browser process (a child process).
            CefRuntime.Initialize(cefMainArgs, cefSettings, cefApp, IntPtr.Zero);

            // Instruct CEF to not render to a window.
            CefWindowInfo cefWindowInfo = CefWindowInfo.Create();
            cefWindowInfo.SetAsWindowless(IntPtr.Zero, false);

            // Settings for the browser window itself (e.g. enable JavaScript?).
            CefBrowserSettings cefBrowserSettings = new CefBrowserSettings()
            {
                BackgroundColor           = new CefColor(255, 60, 85, 115),
                JavaScript                = CefState.Enabled,
                JavaScriptAccessClipboard = CefState.Disabled,
                JavaScriptCloseWindows    = CefState.Disabled,
                JavaScriptDomPaste        = CefState.Disabled,
                JavaScriptOpenWindows     = CefState.Disabled,
                LocalStorage              = CefState.Disabled
            };

            // Initialize some of the custom interactions with the browser process.
            this.cefClient = new OffscreenCEFClient(this.windowSize, this.hideScrollbars);

            // Start up the browser instance.
            CefBrowserHost.CreateBrowser(cefWindowInfo, this.cefClient, cefBrowserSettings, string.IsNullOrEmpty(this.url) ? "http://www.google.com" : this.url);
        }
示例#6
0
            protected override bool OnBeforePopup(CefBrowser browser, CefFrame frame, string targetUrl, string targetFrameName,
                                                  CefWindowOpenDisposition targetDisposition, bool userGesture, CefPopupFeatures popupFeatures,
                                                  CefWindowInfo windowInfo, ref CefClient client, CefBrowserSettings settings, ref bool noJavascriptAccess)
            {
                //settings.WebSecurity = CefState.Disabled;
                windowInfo.SetAsWindowless(IntPtr.Zero, false);
                var newBrowser = new Browser(false);

                client = newBrowser.CefClient;

                WaitForBrowser(newBrowser);

                return(false);
            }
示例#7
0
        internal Browser(V8ScriptEngine father, Size browserSize, bool localMode)
        {
            Father = father;
            if (!CefUtil.DISABLE_CEF)
            {
                LogManager.CefLog("--> Browser: Start");
                CefWindowInfo cefWindowinfo = CefWindowInfo.Create();
                cefWindowinfo.SetAsWindowless(IntPtr.Zero, true);
                cefWindowinfo.TransparentPaintingEnabled = true;
                cefWindowinfo.WindowlessRenderingEnabled = true;


                var browserSettings = new CefBrowserSettings()
                {
                    JavaScriptCloseWindows = CefState.Disabled,
                    JavaScriptOpenWindows  = CefState.Disabled,
                    WindowlessFrameRate    = CEFManager.FPS,
                    FileAccessFromFileUrls = CefState.Disabled,
                };

                _client = new MainCefClient(browserSize.Width, browserSize.Height);

                _client.OnCreated += (sender, args) =>
                {
                    _browser = (CefBrowser)sender;
                    LogManager.CefLog("-> Browser created!");
                };

                Size       = browserSize;
                _localMode = localMode;
                _callback  = new BrowserJavascriptCallback(father, this);
                try
                {
                    LogManager.CefLog("--> Browser: Creating Browser");
                    CefBrowserHost.CreateBrowser(cefWindowinfo, _client, browserSettings);
                }
                catch (Exception e)
                {
                    LogManager.CefLog(e, "CreateBrowser");
                }
                LogManager.CefLog("--> Browser: End");
            }
        }
        // Use this for initialization
        void Start()
        {
            this.BrowserTexture = new Texture2D(this.windowSize.Width, this.windowSize.Height, TextureFormat.BGRA32, false);

            if (GetComponent <RawImage>() != null)
            {
                GetComponent <RawImage>().texture = BrowserTexture;
            }
            if (GetComponent <MeshRenderer>() != null)
            {
                GetComponent <MeshRenderer>().material.mainTexture = BrowserTexture;
            }

#if !UNITY_EDITOR
            // Instruct CEF to not render to a window.
            CefWindowInfo cefWindowInfo = CefWindowInfo.Create();
            cefWindowInfo.SetAsWindowless(IntPtr.Zero, false);

            // Settings for the browser window itself (e.g. enable JavaScript?).
            CefBrowserSettings cefBrowserSettings = new CefBrowserSettings()
            {
                BackgroundColor           = new CefColor(255, 60, 85, 115),
                JavaScript                = CefState.Enabled,
                JavaScriptAccessClipboard = CefState.Disabled,
                JavaScriptCloseWindows    = CefState.Disabled,
                JavaScriptDomPaste        = CefState.Disabled,
                JavaScriptOpenWindows     = CefState.Disabled,
                LocalStorage              = CefState.Disabled
            };

            // Initialize some of the custom interactions with the browser process.
            this.cefClient = new OffscreenCEFClient(this.windowSize, this.hideScrollbars);

            // Start up the browser instance.
            CefBrowserHost.CreateBrowser(cefWindowInfo, this.cefClient, cefBrowserSettings, string.IsNullOrEmpty(this.url) ? "http://www.google.com" : this.url);
#endif
            StartCoroutine(UpdateTexture());
            StartCoroutine(MessagePump());
        }
示例#9
0
        /// <summary>
        /// 创建cef 打开的——blank实例
        /// </summary>
        public static Task <CookiedCefBrowser> CreateNewWebBrowser()
        {
            //使用任务 锁保证事件变为同步
            var tcs = new TaskCompletionSource <CookiedCefBrowser>();

            // Instruct CEF to not render to a window at all.
            CefWindowInfo cefWindowInfo = CefWindowInfo.Create();

            cefWindowInfo.SetAsWindowless(IntPtr.Zero, true);

            // Settings for the browser window itself (e.g. should JavaScript be enabled?).
            var cefBrowserSettings = new CefBrowserSettings();

            // Initialize some the cust interactions with the browser process.
            // The browser window will be 1280 x 720 (pixels).
            var cefClient = new HeadLessCefClient(1, 1);
            var loader    = cefClient.GetCurrentLoadHandler();

            loader.BrowserCreated += (s, e) =>
            {
                //事件通知 当cef  browser 创建完毕
                //创建完毕后 保存 browser 对象的实例
                var brw         = e.Browser;
                var etaoBrowser = new CookiedCefBrowser {
                    CefBrowser = brw, CefLoader = loader, CefClient = cefClient
                };

                tcs.TrySetResult(etaoBrowser);
            };
            ////注册  加载完毕事件handler
            //loader.LoadEnd += this.OnWebBrowserLoadEnd;
            // Start up the browser instance.
            string url = "about:blank";

            CefBrowserHost.CreateBrowser(cefWindowInfo, cefClient, cefBrowserSettings, url);

            return(tcs.Task);
        }
            private Task <TestCefGlueHTMLWindowProvider> InitTask(string ipath)
            {
                TaskCompletionSource <TestCefGlueHTMLWindowProvider> tcs = new TaskCompletionSource <TestCefGlueHTMLWindowProvider>();

                Task.Run(() =>
                {
                    CefCoreSessionSingleton.GetAndInitIfNeeded();

                    CefWindowInfo cefWindowInfo = CefWindowInfo.Create();
                    cefWindowInfo.SetAsWindowless(IntPtr.Zero, true);

                    // Settings for the browser window itself (e.g. enable JavaScript?).
                    var cefBrowserSettings = new CefBrowserSettings();

                    // Initialize some the cust interactions with the browser process.
                    var cefClient = new TestCefClient();

                    ipath           = ipath ?? "javascript\\index.html";
                    string fullpath = string.Format("{0}\\{1}", Assembly.GetExecutingAssembly().GetPath(), ipath);

                    // Start up the browser instance.
                    CefBrowserHost.CreateBrowser(cefWindowInfo, cefClient, cefBrowserSettings, fullpath);

                    cefClient.GetLoadedBroserAsync().ContinueWith(t =>
                    {
                        var frame               = t.Result.GetMainFrame();
                        var context             = CefCoreSessionSingleton.Session.CefApp.GetContext(frame);
                        _Father._ICefGlueWindow = new TestCefGlueHTMLWindowProvider(frame);
                        tcs.SetResult(_Father._ICefGlueWindow);
                    }
                                                                  );
                }
                         );

                return(tcs.Task);
            }
示例#11
0
        public bool CreateBrowser(BrowserSource browserSource,
                                  BrowserConfig browserConfig)
        {
            if (browserClient == null)
            {
                InitClient(browserSource);
            }

            Debug.Assert(browserClient != null);
            Debug.Assert(browserConfig != null);

            BrowserConfig = browserConfig;

            CefWindowInfo windowInfo = CefWindowInfo.Create();

            windowInfo.Width  = (int)browserConfig.BrowserSourceSettings.Width;
            windowInfo.Height = (int)browserConfig.BrowserSourceSettings.Height;
            windowInfo.SetAsWindowless(IntPtr.Zero, true);

            BrowserInstanceSettings settings = AbstractSettings.DeepClone(
                BrowserSettings.Instance.InstanceSettings);

            settings.MergeWith(browserConfig.BrowserInstanceSettings);

            CefBrowserSettings browserSettings = new CefBrowserSettings
            {
                WindowlessFrameRate        = browserConfig.BrowserSourceSettings.Fps,
                ApplicationCache           = settings.ApplicationCache,
                CaretBrowsing              = settings.CaretBrowsing,
                CursiveFontFamily          = settings.CursiveFontFamily,
                Databases                  = settings.Databases,
                DefaultEncoding            = settings.DefaultEncoding,
                DefaultFixedFontSize       = settings.DefaultFixedFontSize,
                DefaultFontSize            = settings.DefaultFontSize,
                FantasyFontFamily          = settings.FantasyFontFamily,
                FileAccessFromFileUrls     = settings.FileAccessFromFileUrls,
                FixedFontFamily            = settings.FixedFontFamily,
                ImageLoading               = settings.ImageLoading,
                ImageShrinkStandaloneToFit = settings.ImageShrinkStandaloneToFit,
                Java       = settings.Java,
                JavaScript = settings.JavaScript,
                JavaScriptAccessClipboard = settings.JavaScriptAccessClipboard,
                JavaScriptCloseWindows    = settings.JavaScriptCloseWindows,
                JavaScriptDomPaste        = settings.JavaScriptDomPaste,
                JavaScriptOpenWindows     = settings.JavaScriptOpenWindows,
                LocalStorage           = settings.LocalStorage,
                MinimumFontSize        = settings.MinimumFontSize,
                MinimumLogicalFontSize = settings.MinimumLogicalFontSize,
                Plugins             = settings.Plugins,
                RemoteFonts         = settings.RemoteFonts,
                SansSerifFontFamily = settings.SansSerifFontFamily,
                SerifFontFamily     = settings.SerifFontFamily,
                StandardFontFamily  = settings.StandardFontFamily,
                //TabToLinks = settings.TabToLinks,
                //TextAreaResize = settings.TextAreaResize,
                UniversalAccessFromFileUrls =
                    settings.UniversalAccessFromFileUrls,
                WebGL       = settings.WebGL,
                WebSecurity = settings.WebSecurity
            };

            String url = browserConfig.BrowserSourceSettings.Url;

            if (browserConfig.BrowserSourceSettings.IsApplyingTemplate)
            {
                url = "http://absolute";
            }

            lock (browserLock)
            {
                ManualResetEventSlim createdBrowserEvent =
                    new ManualResetEventSlim();
                CefRuntime.PostTask(CefThreadId.UI, BrowserTask.Create(() =>
                {
                    try
                    {
                        browser = CefBrowserHost.CreateBrowserSync(windowInfo,
                                                                   browserClient, browserSettings, new Uri(url));
                        BrowserManager.Instance.RegisterBrowser(browser.Identifier,
                                                                this);

                        // request the render process id for volume control
                        browser.SendProcessMessage(CefProcessId.Renderer,
                                                   CefProcessMessage.Create("renderProcessIdRequest"));
                    }
                    catch (Exception)
                    {
                        browser = null;
                    }
                    finally
                    {
                        createdBrowserEvent.Set();
                    }
                }));
                createdBrowserEvent.Wait();
            }

            return(browser != null);
        }
示例#12
0
        /// <summary>
        ///		Starts CEF
        /// </summary>
        /// <exception cref="Exception"></exception>
        public void Init()
        {
            // ReSharper disable once RedundantAssignment
            string[] argv = args;
#if LINUX
            //On Linux we need to do this, otherwise it will just crash, no idea why tho
            argv = new string[args.Length + 1];
            Array.Copy(args, 0, argv, 1, args.Length);
            argv[0] = "-";
#endif

            //Set up CEF args and the CEF app
            CefMainArgs          cefMainArgs = new CefMainArgs(argv);
            BrowserProcessCEFApp cefApp      = new BrowserProcessCEFApp(launchArguments);

            //Run our sub-processes
            int exitCode = CefRuntime.ExecuteProcess(cefMainArgs, cefApp, IntPtr.Zero);
            if (exitCode != -1)
            {
                Environment.Exit(exitCode);
                return;
            }

            //Backup
            if (argv.Any(arg => arg.StartsWith("--type=")))
            {
                Environment.Exit(-2);
                return;
            }

            //Do we have a cache or not, if not CEF will run in "incognito" mode.
            string cachePathArgument = null;
            if (launchArguments.CachePath != null)
            {
                cachePathArgument = launchArguments.CachePath.FullName;
            }

            //Convert UnityWebBrowser log severity to CefLogSeverity
            CefLogSeverity logSeverity = launchArguments.LogSeverity switch
            {
                LogSeverity.Debug => CefLogSeverity.Debug,
                LogSeverity.Info => CefLogSeverity.Info,
                LogSeverity.Warn => CefLogSeverity.Warning,
                LogSeverity.Error => CefLogSeverity.Error,
                LogSeverity.Fatal => CefLogSeverity.Fatal,
                _ => CefLogSeverity.Default
            };

            //Setup the CEF settings
            CefSettings cefSettings = new CefSettings
            {
                WindowlessRenderingEnabled = true,
                NoSandbox = true,
                LogFile   = launchArguments.LogPath.FullName,
                CachePath = cachePathArgument,

                //TODO: On MacOS multi-threaded message loop isn't supported
                MultiThreadedMessageLoop = true,
                LogSeverity         = logSeverity,
                Locale              = "en-US",
                ExternalMessagePump = false,
                RemoteDebuggingPort = launchArguments.RemoteDebugging,
#if LINUX
                //On Linux we need to tell CEF where everything is, this will assume that the working directory is where everything is!
                ResourcesDirPath      = System.IO.Path.Combine(Environment.CurrentDirectory),
                LocalesDirPath        = System.IO.Path.Combine(Environment.CurrentDirectory, "locales"),
                BrowserSubprocessPath = Environment.GetCommandLineArgs()[0]
#endif
            };

            //Init CEF
            CefRuntime.Initialize(cefMainArgs, cefSettings, cefApp, IntPtr.Zero);

            //Create a CEF window and set it to windowless
            CefWindowInfo cefWindowInfo = CefWindowInfo.Create();
            cefWindowInfo.SetAsWindowless(IntPtr.Zero, false);

            //Create our CEF browser settings
            CefColor backgroundColor = new CefColor(launchArguments.Bca, launchArguments.Bcr, launchArguments.Bcg,
                                                    launchArguments.Bcb);
            CefBrowserSettings cefBrowserSettings = new CefBrowserSettings
            {
                BackgroundColor = backgroundColor,
                JavaScript      = launchArguments.JavaScript ? CefState.Enabled : CefState.Disabled,
                LocalStorage    = CefState.Disabled
            };

            Logger.Debug($"CEF starting with these options:" +
                         $"\nJS: {launchArguments.JavaScript}" +
                         $"\nBackgroundColor: {backgroundColor}" +
                         $"\nCache Path: {cachePathArgument}" +
                         $"\nLog Path: {launchArguments.LogPath.FullName}" +
                         $"\nLog Severity: {launchArguments.LogSeverity}");
            Logger.Info("Starting CEF client...");

            //Create cef browser
            cefClient = new BrowserProcessCEFClient(new CefSize(launchArguments.Width, launchArguments.Height),
                                                    new ProxySettings(launchArguments.ProxyUsername, launchArguments.ProxyPassword, launchArguments.ProxyEnabled));
            CefBrowserHost.CreateBrowser(cefWindowInfo, cefClient, cefBrowserSettings, launchArguments.InitialUrl);

            cefClient.OnUrlChange += OnUrlChange;
        }
示例#13
0
        protected virtual void OnCreateBrowser()
        {
            if (this.Opener != null)
            {
                return;
            }

            if (GetState(State.Creating) || GetState(State.Created))
            {
                throw new InvalidOperationException();
            }

            SetState(State.Creating, true);

            Dictionary <InitialPropertyKeys, object> propertyBag = InitialPropertyBag;

            InitialPropertyBag = null;

            var avaloniaWindow = this.GetVisualRoot() as Window;

            if (avaloniaWindow is null)
            {
                throw new InvalidOperationException("Window not found!");
            }

            using (var windowInfo = new CefWindowInfo())
            {
                IPlatformHandle platformHandle = avaloniaWindow.PlatformImpl.Handle;
                if (platformHandle is IMacOSTopLevelPlatformHandle macOSHandle)
                {
                    windowInfo.SetAsWindowless(macOSHandle.GetNSWindowRetained());
                }
                else
                {
                    windowInfo.SetAsWindowless(platformHandle.Handle);
                }

                string             initialUrl      = null;
                CefDictionaryValue extraInfo       = null;
                CefRequestContext  requestContext  = null;
                CefBrowserSettings browserSettings = null;
                if (propertyBag != null)
                {
                    object value;
                    if (propertyBag.TryGetValue(InitialPropertyKeys.Url, out value))
                    {
                        initialUrl = value as string;
                    }
                    if (propertyBag.TryGetValue(InitialPropertyKeys.BrowserSettings, out value))
                    {
                        browserSettings = value as CefBrowserSettings;
                    }
                    if (propertyBag.TryGetValue(InitialPropertyKeys.RequestContext, out value))
                    {
                        requestContext = value as CefRequestContext;
                    }
                    if (propertyBag.TryGetValue(InitialPropertyKeys.ExtraInfo, out value))
                    {
                        extraInfo = value as CefDictionaryValue;
                    }
                }

                if (initialUrl == null)
                {
                    initialUrl = "about:blank";
                }
                if (browserSettings == null)
                {
                    browserSettings = DefaultBrowserSettings;
                }

                if (!CefApi.CreateBrowser(windowInfo, ViewGlue.Client, initialUrl, browserSettings, extraInfo, requestContext))
                {
                    throw new InvalidOperationException("Failed to create browser instance.");
                }
            }
        }
示例#14
0
        protected virtual void OnCreateBrowser()
        {
            if (this.Opener != null)
            {
                return;
            }

            if (GetState(State.Creating) || GetState(State.Created))
            {
                throw new InvalidOperationException();
            }

            SetState(State.Creating, true);

            Dictionary <InitialPropertyKeys, object> propertyBag = InitialPropertyBag;

            InitialPropertyBag = null;

            var wpfwindow = System.Windows.Window.GetWindow(this);

            if (wpfwindow == null)
            {
                throw new InvalidOperationException("Window not found!");
            }

            using (var windowInfo = new CefWindowInfo())
            {
                windowInfo.SetAsWindowless(new WindowInteropHelper(wpfwindow).Handle);

                string             initialUrl      = null;
                CefDictionaryValue extraInfo       = null;
                CefRequestContext  requestContext  = null;
                CefBrowserSettings browserSettings = null;
                if (propertyBag != null)
                {
                    object value;
                    if (propertyBag.TryGetValue(InitialPropertyKeys.Url, out value))
                    {
                        initialUrl = value as string;
                    }
                    if (propertyBag.TryGetValue(InitialPropertyKeys.BrowserSettings, out value))
                    {
                        browserSettings = value as CefBrowserSettings;
                    }
                    if (propertyBag.TryGetValue(InitialPropertyKeys.RequestContext, out value))
                    {
                        requestContext = value as CefRequestContext;
                    }
                    if (propertyBag.TryGetValue(InitialPropertyKeys.ExtraInfo, out value))
                    {
                        extraInfo = value as CefDictionaryValue;
                    }
                }

                if (initialUrl == null)
                {
                    initialUrl = "about:blank";
                }
                if (browserSettings == null)
                {
                    browserSettings = DefaultBrowserSettings;
                }

                if (!CefApi.CreateBrowser(windowInfo, ViewGlue.Client, initialUrl, browserSettings, extraInfo, requestContext))
                {
                    throw new InvalidOperationException("Failed to create browser instance.");
                }
            }
        }
示例#15
0
        /// <summary>
        /// 创建cef,并 打开制定的网址
        /// </summary>
        /// <param name="url"></param>
        /// <param name="handlerRequest"></param>
        /// <param name="timeOut"></param>
        /// <returns></returns>
        public static Task <CookiedCefBrowser> CreateNewWebBrowser(string url, EventHandler <LoadEndEventArgs> handlerRequest, int timeOut = 5000)
        {
            //验证是否是合法的URL
            var isUrl = InPutValidate.IsUrl(url);

            if (!isUrl)
            {
                return(Task.FromResult <CookiedCefBrowser>(null));
            }
            //使用任务 锁保证事件变为同步
            var tcs = new TaskCompletionSource <CookiedCefBrowser>();


            // Instruct CEF to not render to a window at all.
            CefWindowInfo cefWindowInfo = CefWindowInfo.Create();

            cefWindowInfo.SetAsWindowless(IntPtr.Zero, true);

            // Settings for the browser window itself (e.g. should JavaScript be enabled?).
            var cefBrowserSettings = new CefBrowserSettings();

            // Initialize some the cust interactions with the browser process.
            // The browser window will be 1280 x 720 (pixels).
            var cefClient = new HeadLessCefClient(1, 1);
            var loader    = cefClient.GetCurrentLoadHandler();

            loader.BrowserCreated += (s, e) =>
            {
                //事件通知 当cef  browser 创建完毕
                //创建完毕后 保存 browser 对象的实例
                var brw         = e.Browser;
                var etaoBrowser = new CookiedCefBrowser {
                    CefBrowser = brw, CefLoader = loader, CefClient = cefClient
                };

                tcs.TrySetResult(etaoBrowser);
            };
            if (null != handlerRequest)
            {
                loader.LoadEnd += handlerRequest;
            }
            ////注册  加载完毕事件handler
            //loader.LoadEnd += this.OnWebBrowserLoadEnd;
            // Start up the browser instance.
            // string url = "about:blank";
            CefBrowserHost.CreateBrowser(cefWindowInfo, cefClient, cefBrowserSettings, url);

            //设定超时
            //超时监听

            int timeoutMs = timeOut;
            var ctoken    = new CancellationTokenSource(timeoutMs);

            ctoken.Token.Register(() =>
            {
                var brw         = loader.Browser;
                var etaoBrowser = new CookiedCefBrowser {
                    CefBrowser = brw, CefLoader = loader, CefClient = cefClient
                };

                //超时结果返回空
                tcs.TrySetResult(etaoBrowser);

                //tcs.TrySetCanceled();
            }, useSynchronizationContext: false);

            return(tcs.Task);
        }
示例#16
0
        internal static void Main(string[] args)
        {
#if false
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
#endif


            int bitness = System.IntPtr.Size * 8;
            System.Console.WriteLine($"Running as {bitness}-Bit application");

            // New idea:

            // Chrome v59 now supports headless mode which has some interesting flags.
            // Running with --screenshot will produce a file named screenshot.png in the current working directory:

            // cd C:\Program Files(x86)\Google\Chrome\Application
            // chrome --headless --screenshot https://www.chromestatus.com/

            // # Size of a standard letterhead.
            // chrome --headless --screenshot --window-size=1280,1696 https://www.chromestatus.com/

            // # Nexus 5x
            // chrome --headless --screenshot --window-size=412,732 https://www.chromestatus.com/


            // https://developers.google.com/web/updates/2017/04/headless-chrome
            // The --dump-dom flag prints document.body.innerHTML to stdout:
            // chrome --headless --disable-gpu --dump-dom https://www.chromestatus.com/

            // The --print-to-pdf flag creates a PDF of the page:
            // chrome --headless --disable-gpu --print-to-pdf https://www.chromestatus.com/

            // chrome --headless --disable-gpu --repl --crash-dumps-dir=./tmp https://www.chromestatus.com/
            // [0608 / 112805.245285:INFO: headless_shell.cc(278)] Type a Javascript expression to evaluate or "quit" to exit.
            // >>> location.href
            // { "result":{ "type":"string","value":"https://www.chromestatus.com/features"} }
            // >>> quit


            // CefFiles.DownloadCefForPlatform(@"D:\inetpub\mycef");
            // CefFiles.DownloadCefForPlatform(@"/root/Downloads/CEF/download.tar.bz2");



            // CefFiles.Cleanup(); return;

            // Load CEF. This checks for the correct CEF version.

            System.Console.WriteLine("Loading CEF");
            CefRuntime.Load();
            System.Console.WriteLine("CEF loaded");

            // Start the secondary CEF process.
            System.Console.WriteLine("New MainArgs");

            string[] argv = args;

            // https://github.com/dotnet/coreclr/issues/23171
            if (CefRuntime.Platform != CefRuntimePlatform.Windows)
            {
                argv = new string[args.Length + 1];
                System.Array.Copy(args, 0, argv, 1, args.Length);
                argv[0] = "-";
            }

            CefMainArgs cefMainArgs = new CefMainArgs(argv);
            System.Console.WriteLine("New MainArgs completed");

            System.Console.WriteLine("New DemoCefApp ");
            DemoCefApp cefApp = new DemoCefApp();
            System.Console.WriteLine("New DemoCefApp completed");



            System.Console.WriteLine("Before executing process");
            // This is where the code path divereges for child processes.
            if (CefRuntime.ExecuteProcess(cefMainArgs, cefApp, System.IntPtr.Zero) != -1)
            {
                System.Console.WriteLine("Could not start the secondary process");
                System.Console.Error.WriteLine("Could not start the secondary process.");
            }
            System.Console.WriteLine("After executing process");


            System.Console.WriteLine("Before new CEF-settings");
            // Settings for all of CEF (e.g. process management and control).
            CefSettings cefSettings = new CefSettings
            {
                // From v68 SingleProcess is no longer supported and it has to be published.
                // So debugging may be a tough situation in that regard unless your had a subprocess.
                // SingleProcess = false, // https://github.com/chromelyapps/Chromely/issues/74
                MultiThreadedMessageLoop = CefRuntime.Platform == CefRuntimePlatform.Windows,
                LogSeverity                = CefLogSeverity.Verbose,
                LogFile                    = "cef.log",
                ResourcesDirPath           = System.IO.Path.GetDirectoryName(new System.Uri(System.Reflection.Assembly.GetEntryAssembly().CodeBase).LocalPath),
                RemoteDebuggingPort        = 20480,
                WindowlessRenderingEnabled = true,
                NoSandbox                  = true,
                IgnoreCertificateErrors    = true,
                CommandLineArgsDisabled    = false,
            };
            System.Console.WriteLine("After new CEF-settings");


            System.Console.WriteLine("Before CEF initialize");
            // Start the browser process (a child process).
            // runtime files to /usr/share/dotnet
            CefRuntime.Initialize(cefMainArgs, cefSettings, cefApp, System.IntPtr.Zero);
            System.Console.WriteLine("After CEF initialize");



            System.Console.WriteLine("Before CEF Window Create");
            // Instruct CEF to not render to a window at all.
            CefWindowInfo cefWindowInfo = CefWindowInfo.Create();
            System.Console.WriteLine("After CEF Window Create");

            // cefWindowInfo.SetAsOffScreen(IntPtr.Zero);
            cefWindowInfo.WindowlessRenderingEnabled = true;
            cefWindowInfo.SetAsWindowless(System.IntPtr.Zero, true);



            System.Console.WriteLine("New CefBrowserSettings");
            // Settings for the browser window itself (e.g. enable JavaScript?).
            CefBrowserSettings cefBrowserSettings = new CefBrowserSettings();
            System.Console.WriteLine("After New CefBrowserSettings");



            cefBrowserSettings.WebGL = CefState.Disabled;
            cefBrowserSettings.WindowlessFrameRate = 30;

            /*
             * cefBrowserSettings.Plugins = CefState.Disabled;
             * cefBrowserSettings.DefaultEncoding = System.Text.Encoding.UTF8.WebName;
             * cefBrowserSettings.JavaScriptCloseWindows = CefState.Disabled;
             * cefBrowserSettings.JavaScriptAccessClipboard = CefState.Disabled;
             * cefBrowserSettings.JavaScriptDomPaste = CefState.Disabled;
             * cefBrowserSettings.JavaScript = CefState.Enabled;
             */


            // CefRuntime.RunMessageLoop();


            System.Console.WriteLine("Before new DemoClient");


            // Initialize some the cust interactions with the browser process.
            // The browser window will be 1280 x 720 (pixels).
            DemoCefClient cefClient = new DemoCefClient(1280, 720);

            System.Console.WriteLine("After new DemoClient");

            System.Console.WriteLine("Before CreateBrowser");
            // Start up the browser instance.
            CefBrowserHost.CreateBrowser(
                cefWindowInfo,
                cefClient,
                cefBrowserSettings,
                // "https://www.microsoft.com/de-CH"
                // "https://google.com"
                "http://www.reddit.com/"
                );


            System.Console.WriteLine("After CreateBrowser");


            // Hang, to let the browser to do its work.
            System.Console.WriteLine(System.Environment.NewLine);
            System.Console.WriteLine(" --- Press a key at any time to end the program. --- ");
            System.Console.ReadKey();


            System.Console.WriteLine("Before CefShutdown");

            // Clean up CEF.
            CefRuntime.Shutdown();
            System.Console.WriteLine("After CefShutdown");
        } // End Sub Main