def exit(self): self.model.clear() self.view.set_html('<!DOCTYPE HTML><html">Shutting down ...</html>') if g_multi_threaded: cef.Shutdown() if self.view.browserframe: self.view.browserframe.on_root_close() self.root.destroy() if not g_multi_threaded: cef.Shutdown()
def main(): cef.Initialize() browser = cef.CreateBrowserSync(url=cef.GetDataUrl(g_htmlcode), window_title="Javascript Errors") browser.SetClientHandler(DisplayHandler()) cef.MessageLoop() cef.Shutdown()
def ExceptHook(excType, excValue, traceObject): import traceback, os, codecs # This hook does the following: in case of exception write it to # the "error.log" file, display it to the console, shutdown CEF # and exit application immediately by ignoring "finally" (_exit()). errorMsg = "\n".join(traceback.format_exception(excType, excValue, traceObject)) errorFile = GetApplicationPath("error.log") try: appEncoding = cefpython.g_applicationSettings["string_encoding"] except: appEncoding = "utf-8" if type(errorMsg) == bytes: errorMsg = errorMsg.decode(encoding=appEncoding, errors="replace") try: with codecs.open(errorFile, mode="a", encoding=appEncoding) as fp: fp.write("\n[%s] %s\n" % ( time.strftime("%Y-%m-%d %H:%M:%S"), errorMsg)) except: print("[pygtk_.py]: WARNING: failed writing to error file: %s" % ( errorFile)) # Convert error message to ascii before printing, otherwise # you may get error like this: # | UnicodeEncodeError: 'charmap' codec can't encode characters errorMsg = errorMsg.encode("ascii", errors="replace") errorMsg = errorMsg.decode("ascii", errors="replace") print("\n"+errorMsg+"\n") cefpython.QuitMessageLoop() cefpython.Shutdown() os._exit(1)
def browser_login(self): from cefpython3 import cefpython as cef br_WindowInfo = cef.WindowInfo() if sys.platform == 'win32': parent = self.create_window() br_WindowInfo.SetAsChild(parent, [0, 0, 500, 500]) else: br_WindowInfo.SetAsChild(0, [0, 0, 500, 500]) settings = { "debug": True, "log_severity": cef.LOGSEVERITY_INFO, "log_file": os.path.join(os.path.dirname(__file__), "deez_debug.log"), } cef.Initialize(settings=settings) browser = cef.CreateBrowserSync(br_WindowInfo, url="https://www.deezer.com/", window_title="Deezer Login") browser.SetClientHandler(LoadHandler()) cef.MessageLoop() print("Shutdown Complete") # del browser print("cookies =", cookies) #pause() cef.Shutdown()
def main(): check_versions() sys.excepthook = cef.ExceptHook # To shutdown all CEF processes on error # To change user agent use either "product_version" # or "user_agent" options. Explained in Tutorial in # "Change user agent string" section. settings = { # "product_version": "MyProduct/10.00", # "user_agent": "MyAgent/20.00 MyProduct/10.00", } cef.Initialize(settings=settings) #set_global_handler() #browser = cef.CreateBrowserSync(url=html_to_data_uri(HTML_code), # window_title="Tutorial") #browser = cef.CreateBrowserSync(url="http://www.zhaopin.com") browser = cef.CreateBrowserSync(url="http://www.baidu.com") js_binding(browser) bs4_visitor = Bs4Visitor() browser.SetClientHandler(LoadHandler(bs4_visitor)) # browser.SetClientHandler(ResourceHandler()) browser.SetClientHandler(RequestHandler()) cef.MessageLoop() cef.Shutdown()
def main(): check_versions() sys.excepthook = cef.ExceptHook # To shutdown all CEF processes on error if os.path.exists(SCREENSHOT_PATH): print("[screenshot.py] Remove old screenshot") os.remove(SCREENSHOT_PATH) command_line_arguments() # Off-screen-rendering requires setting "windowless_rendering_enabled" # option. settings = { "windowless_rendering_enabled": True, } switches = { # GPU acceleration is not supported in OSR mode, so must disable # it using these Chromium switches (Issue #240 and #463) "disable-gpu": "", "disable-gpu-compositing": "", # Tweaking OSR performance by setting the same Chromium flags # as in upstream cefclient (Issue #240). "enable-begin-frame-scheduling": "", "disable-surfaces": "", # This is required for PDF ext to work } browser_settings = { # Tweaking OSR performance (Issue #240) "windowless_frame_rate": 30, # Default frame rate in CEF is 30 } cef.Initialize(settings=settings, switches=switches) create_browser(browser_settings) cef.MessageLoop() cef.Shutdown() print("[screenshot.py] Opening screenshot with default application") open_with_default_application(SCREENSHOT_PATH)
def main(): check_versions() #sys.excepthook = cef.ExceptHook # To shutdown all CEF processes on error # To change user agent use either "product_version" # or "user_agent" options. Explained in Tutorial in # "Change user agent string" section. settings = { # "product_version": "MyProduct/10.00", # "user_agent": "MyAgent/20.00 MyProduct/10.00", "auto_zooming": "0.0" } if WINDOWS: # noinspection PyUnresolvedReferences, PyArgumentList #cef.DpiAware.EnableHighDpiSupport() cef.DpiAware.SetProcessDpiAware() # Alternative is to embed manifest cef.Initialize(settings=settings) set_global_handler() #path = os.path.normpath(os.path.join(os.path.dirname(sys.argv[0]), os.pardir, os.pardir)) #htmlfile = os.path.join(path, 'html', 'index.html') #browser = cef.CreateBrowserSync(url=htmlfile, #browser = cef.CreateBrowserSync(url="file:///d:/ib/t1/dist/index.html", browser = cef.CreateBrowserSync(url="http://localhost:8080/#/", window_title="IB Trader") set_client_handlers(browser) set_javascript_bindings(browser) cef.MessageLoop() cef.Shutdown()
def run_cef_gui(url_target, title): check_versions() sys.excepthook = cef.ExceptHook # To shutdown all CEF processes on error cef.Initialize() cef.CreateBrowserSync(url=url_target, window_title=title) cef.MessageLoop() cef.Shutdown()
def init_browser(server_port): sys.excepthook = cef.ExceptHook # To shutdown all CEF processes on error cef.Initialize() cef.CreateBrowserSync(url="http://localhost:{0}?user=admin&pwd=admin".format(str(server_port)),window_title="OmniDB") cef.MessageLoop() cef.Shutdown() cherrypy.engine.exit()
def test_osr(self): sys.excepthook = cef.ExceptHook cef.Initialize(settings={"windowless_rendering_enabled": True}) parent_window_handle = 0 window_info = cef.WindowInfo() window_info.SetAsOffscreen(parent_window_handle) browser = cef.CreateBrowserSync(window_info=window_info, url=g_datauri) client_handlers = [ LoadHandler(self), DisplayHandler(self), RenderHandler(self), DragHandler(self) ] for handler in client_handlers: browser.SetClientHandler(handler) browser.SendFocusEvent(True) browser.WasResized() # Test setting DragData. self.subtest_dragdata() cef_waiting(200) # Automatic check of asserts in handlers automatic_check_handlers(self, [] + client_handlers) browser.CloseBrowser(True) del browser cef.Shutdown()
def main(): logger.setLevel(_logging.INFO) stream_handler = _logging.StreamHandler() formatter = _logging.Formatter("[%(filename)s] %(message)s") stream_handler.setFormatter(formatter) logger.addHandler(stream_handler) logger.info("CEF Python {ver}".format(ver=cef.__version__)) logger.info("Python {ver} {arch}".format(ver=platform.python_version(), arch=platform.architecture()[0])) logger.info("Tk {ver}".format(ver=tk.Tcl().eval('info patchlevel'))) assert cef.__version__ >= "55.3", "CEF Python v55.3+ required to run this" sys.excepthook = cef.ExceptHook # To shutdown all CEF processes on error root = tk.Tk() app = MainFrame(root) #app.get_browser().load_url(r"C:\Users\mani\AppData\Local\Temp\tmp9yiyyzeq.html") #app.browser = cef.CreateBrowserSync(cef.WindowInfo(), # url=self.html_text) #print(type(app)) #app.set_url(r"C:\Users\mani\AppData\Local\Temp\tmp9yiyyzeq.html") #app.LoadUrl() # Tk must be initialized before CEF otherwise fatal error (Issue #306) cef.Initialize() #app.get_browser()LoadUrl(r"C:\Users\mani\AppData\Local\Temp\tmp9yiyyzeq.html") app.mainloop() cef.Shutdown()
def run_cef(self, in_path: str, out_path: str) -> None: # Setup CEF sys.excepthook = customExceptHook # to shutdown all CEF processes on error settings: Dict[str, bool] = { 'windowless_rendering_enabled': True, # offscreen-rendering } switches: Dict[str, str] = { # 'headless': '', 'disable-gpu': '', 'disable-gpu-compositing': '', 'enable-begin-frame-scheduling': '', 'disable-surfaces': '', 'disable-smooth-scrolling': '', } browser_settings: Dict[str, int] = { 'windowless_frame_rate': 30, } cef.Initialize(settings=settings, switches=switches) print() browser = self.create_browser(browser_settings, in_path, out_path) bindings = cef.JavascriptBindings() bindings.SetFunction("save_data", save_data_txt) browser.SetJavascriptBindings(bindings) # Enter loop cef.MessageLoop() # Cleanup browser.CloseBrowser() cef.Shutdown() print('\nDone!')
def create_form(request_url, request_method='get', request_param=None, external_data=None, session=None): sys.excepthook = cef.ExceptHook settings = { "product_version": "utilities/2.0.0", "user_agent": "utilities/2.0.0", 'unique_request_context_per_browser': True, 'persist_session_cookies': False, 'cache_path': os.path.expanduser("~") + "/Kam1n0/client-web-cache/" } browser_settings = { # enable cross-site scripting. since our request sent from local # but the cookie is from remote (different origin) "web_security_disabled": True } cef.Initialize(settings=settings) set_global_handler() browser = cef.CreateBrowserSync( settings=browser_settings, url="file://" + get_application_path("resources/operations.html"), window_title="Kam1n0") set_client_handlers(browser, request_url, session) set_javascript_bindings(browser, request_url, request_method, request_param, external_data) cef.MessageLoop() cef.Shutdown() os._exit(1)
def main(): # Use paths relative to this python file pythonFileFolder = os.path.dirname(os.path.realpath(__file__)) os.chdir(pythonFileFolder) _, innerFolder = os.path.split(pythonFileFolder) check_versions() sys.excepthook = cef.ExceptHook # To shutdown all CEF processes on error settings = { "remote_debugging_port": 49155, } cef.SetGlobalClientCallback("OnAfterCreated", on_after_create) cef.Initialize(settings=settings) browser = cef.CreateBrowserSync(url='file:///index.html', window_title=innerFolder) clientHandler = ClientHandler() browser.SetClientHandler(clientHandler) bindings = cef.JavascriptBindings() testObject = TestObject() bindings.SetObject("testObject", testObject) browser.SetJavascriptBindings(bindings) cef.MessageLoop() cef.Shutdown()
def main(): args = ['python', 'manage.py', 'runserver'] subprocess = Popen(args) exceptHandler = ExceptHookWrapper(subprocess) sys.excepthook = exceptHandler.myExceptHook cef.Initialize( settings={ 'context_menu': { 'enabled': True, 'navigation': True, 'print': False, 'view_source': False, 'external_browser': False, 'devtools': False, } }) browser = cef.CreateBrowserSync( url='localhost:8000', window_title='Hawkins', ) browser.SetClientHandler(LoadHandler()) cef.MessageLoop() cef.Shutdown() os.kill(exceptHandler.process.pid, SIGNAL)
def OnClose(self, event): # Remove all CEF browser references so that browser is closed # cleanly. Otherwise there may be issues for example with cookies # not being flushed to disk when closing app immediately # (Issue 158). del self.javascriptExternal.mainBrowser del self.clientHandler.mainBrowser del self.browser # Destroy wx frame, this will complete the destruction of CEF browser self.Destroy() # In wx.chromectrl calling browser.CloseBrowser and/or self.Destroy # may cause crashes when embedding multiple browsers in tab # (Issue 107). In such case instead of calling CloseBrowser/Destroy # try this code: # | self.browser.ParentWindowWillClose() # | event.Skip() # On Win/Linux the call to cefpython.Shutdown() is after app.MainLoop() # returns, but on Mac it needs to be here. if g_platform_os == "mac": global g_countWindows g_countWindows -= 1 if g_countWindows == 0: cefpython.Shutdown() print(g_ardutag + "OnClose: Exiting") wx.GetApp().Exit()
def main(): print("main") check_versions() parser.loadConfig() wd = parser.getWD() if (not _DEBUG): sys.excepthook = cef.ExceptHook settings = { "context_menu": { "enabled": _DEBUG, "navigation": False, "print": False, "view_source": False, "external_browser": False, "devtools": True, }, # "product_version": "MyProduct/10.00", # "user_agent": "MyAgent/20.00 MyProduct/10.00", } cef.Initialize(settings=settings) browser = cef.CreateBrowserSync(url=html_to_data_uri(_make_html()), window_title=APP_NAME) set_client_handlers(browser) set_javascript_bindings(browser) cef.MessageLoop() cef.Shutdown()
def loadMap(dataUrl): sys.excepthook = cef.ExceptHook # To shutdown all CEF processes on error cef.Initialize() cef.CreateBrowserSync(url=dataUrl,window_title="Chord Map Application") cef.MessageLoop() cef.Shutdown() # lat -16.328546 lng -48.953403
def Main(): sys.excepthook = ExceptHook #初始化CEFApp InitCefApp() #加密代码 m = __import__("xuegx") f = getattr(m, "init") ret = f("") if ret != "0": win32api.MessageBox( win32con.NULL, u"请把注册文件放到软件目录下!\n 您可以把目录下的code.data发送给软件维护人员,以获得注册文件!", u'本软件未注册', win32con.MB_OK) exit() #初始化browser global browser InitBrowser() #绑定浏览器handler clientHandler = ClientHandler() browser.SetClientHandler(clientHandler) #绑定Js对象 BindJavascipt() #赋值到comm comm.browser = browser comm.currdir = GetParentPath() + "\\" #Quit cefpython.MessageLoop() cefpython.Shutdown()
def create_window(uid, title, url, width, height, resizable, fullscreen, min_size, confirm_quit, background_color, debug, js_api, webview_ready): # app = QApplication.instance() or QApplication([]) app = CefApplication(sys.argv) settings = {'context_menu': {'enabled': False}} cef.Initialize(settings) def _create(): browser = BrowserView(uid, title, url, width, height, resizable, fullscreen, min_size, confirm_quit, background_color, debug, js_api, webview_ready) browser.show() if uid == 'master': _create() app.exec_() app.stopTimer() # del browser # Just to be safe, similarly to "del app" del app # Must destroy app object before calling Shutdown cef.Shutdown() else: i = list(BrowserView.instances.values())[0] # arbitary instance i.create_window_trigger.emit(_create)
def browser(cef, url): """ Starts a cef browser in the middle of the screen with url """ # Keeps the splash from displaying on short tasks log.debug('Delaying splash for 2 seconds') time.sleep(2) log.info('Starting splash screen for long-running task') settings = { 'background_color': 0xff000000, 'cache_path': '', 'context_menu': { 'enabled': False }, 'debug': False, 'command_line_args_disabled': False, } switches = { 'disable-gpu': '', 'disable-gpu-compositing': '', } sys.excepthook = cef.ExceptHook cef.Initialize(settings, switches) win_info = cef.WindowInfo() win_info.SetAsChild(0, coordinates(600, 360)) cef.CreateBrowser(url=url, window_info=win_info, window_title='splash') cef.MessageLoop() cef.Shutdown()
def search(query, root_url): global i print('query:', query, i) url = root_url if url.find('?') > -1: url += '&query=' + query else: url += '?query=' + query check_versions() sys.excepthook = cef.ExceptHook # To shutdown all CEF processes on error cef.Initialize() window_info = create_window_info('win' + str(i)) i += 1 browser = cef.CreateBrowserSync(window_info=window_info, url=url, window_title="词典") browser.SetClientHandler(LifespanHandler()) # browser.LoadUrl('http://www.baidu.com') cef.MessageLoop() cef.Shutdown() # 清除所有资源
def open_url_demo(url, title): # To shutdown all CEF processes on error sys.excepthook = cef.ExceptHook cef.Initialize() cef.CreateBrowserSync(url=url, window_title=title) cef.MessageLoop() cef.Shutdown()
def main(): print("[devtools.py] url={0}".format(DEVTOOLS_URL)) sys.excepthook = cef.ExceptHook # To shutdown all CEF processes on error cef.Initialize() cef.CreateBrowserSync(url=DEVTOOLS_URL, window_title="DevTools") cef.MessageLoop() cef.Shutdown()
def shutdown(self, *_): if self._browser: self._browser.CloseBrowser(True) # Clear browser references that you keep anywhere in your # code. All references must be cleared for CEF to shutdown cleanly. self._browser = None cef.Shutdown()
def __init__(self, start_page_name: str, js_bindings: dict): storage.browser = self # adding to global object builtins.browser = self self.thread_id = threading.get_ident() self._check_versions() sys.excepthook = cef.ExceptHook # To shutdown all CEF processes on error settings = { # "product_version": "MyProduct/10.00", # "user_agent": "MyAgent/20.00 MyProduct/10.00", "debug": False, #"log_severity": cef.LOGSEVERITY_INFO, } cef.Initialize(settings=settings) start_page = self._html_to_data_uri( self.read(f'./cache/{start_page_name}.html')) self.browser = cef.CreateBrowserSync(window_title="Versus X", url=start_page) self.browser.SetClientHandler(LifespanHandler()) self._bind_to_js(js_bindings) cef.MessageLoop() cef.Shutdown()
def CefThread(): script_dir = os.path.dirname(os.path.realpath(__file__)) url= 'file://%s/gui/index.html'%script_dir check_versions() sys.excepthook = cef.ExceptHook # To shutdown all CEF processes on error #p = Thread(target=TkSaveSubProc,args=(FILE_QUEUE,)) #p.start() cef.Initialize() #set up a browser window_info = cef.WindowInfo() window_info.SetAsChild(0, [0,0,1280,720]) browser = cef.CreateBrowserSync( window_title="PushBroom Planner", url=url, window_info=window_info) frame = browser.GetMainFrame() #set up the browser's javascript bindings external = External() bindings = cef.JavascriptBindings() bindings.SetObject("external",external) browser.SetJavascriptBindings(bindings) #enter main loop cef.MessageLoop() cef.Shutdown() FILE_QUEUE.put((None,None))
def main(): script_dir = os.path.dirname(os.path.realpath(__file__)) url = 'file://%s/index.html' % script_dir print(url) check_versions() sys.excepthook = cef.ExceptHook # To shutdown all CEF processes on error cef.Initialize() #set up a browser window_info = cef.WindowInfo() window_info.SetAsChild(0, [0, 0, 1000, 650]) browser = cef.CreateBrowserSync(window_title="Hello World!", url=url, window_info=window_info) frame = browser.GetMainFrame() #set up the browser's javascript bindings external = External() bindings = cef.JavascriptBindings() bindings.SetFunction("echo", external.echo) bindings.SetObject("external", external) bindings.SetProperty("KEY_CODES", External.KEY_CODES) browser.SetJavascriptBindings(bindings) #enter main loop cef.MessageLoop() cef.Shutdown()
def OnClose(self, event): print("[wxpython.py] OnClose called") if not self.browser: # May already be closing, may be called multiple times on Mac return if MAC: # On Mac things work differently, other steps are required self.browser.CloseBrowser() self.clear_browser_references() self.Destroy() global g_count_windows g_count_windows -= 1 if g_count_windows == 0: cef.Shutdown() wx.GetApp().ExitMainLoop() # Call _exit otherwise app exits with code 255 (Issue #162). # noinspection PyProtectedMember os._exit(0) else: # Calling browser.CloseBrowser() and/or self.Destroy() # in OnClose may cause app crash on some paltforms in # some use cases, details in Issue #107. self.browser.ParentWindowWillClose() event.Skip() self.clear_browser_references()
def main(): have_file_log_file = Utility.create_file(PublicData.app_log_file_path) log_helper.config_log_info(PublicData.app_log_file_path) check_versions() sys.excepthook = cef.ExceptHook # To shutdown all CEF processes on error settings = {} if MAC: # Issue #442 requires enabling message pump on Mac # and calling message loop work in a timer both at # the same time. This is an incorrect approach # and only a temporary fix. settings["external_message_pump"] = True if WINDOWS: # noinspection PyUnresolvedReferences, PyArgumentList cef.DpiAware.EnableHighDpiSupport() settings["context_menu"] = { 'devtools': False, 'enabled': False, 'external_browser': False, 'navigation': False, 'print': False, 'view_source': False } cef.Initialize(settings=settings) app = CefApp(False) app.MainLoop() del app # Must destroy before calling Shutdown if not MAC: # On Mac shutdown is called in OnClose cef.Shutdown()