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 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 _create(): real_url = 'data:text/html,{0}'.format(window.html) if window.html else window.real_url or 'data:text/html,{0}'.format(default_html) cef_browser = cef.CreateBrowserSync(window_info=window_info, url=real_url) browser = Browser(window, handle, cef_browser) bindings = cef.JavascriptBindings() bindings.SetObject('external', browser.js_bridge) bindings.SetFunction('alert', alert_func) cef_browser.SetJavascriptBindings(bindings) cef_browser.SetClientHandler(LoadHandler()) instances[window.uid] = browser window.shown.set() if window.icon: icon = window.icon+".ico" if os.path.isfile(icon): smallx = windll.user32.GetSystemMetrics(49) #SM_CXSMICON smally = windll.user32.GetSystemMetrics(50) #SM_CYSMICON small_icon = windll.user32.LoadImageW(0, icon, 1, smallx, smally, 0x00000010) windll.user32.SendMessageW(handle, 0x0080, 0, small_icon) bigx = windll.user32.GetSystemMetrics(11) #SM_CXICON bigy = windll.user32.GetSystemMetrics(12) #SM_CYICON big_icon = windll.user32.LoadImageW(0, icon, 1, bigx, bigy, 0x00000010) windll.user32.SendMessageW(handle, 0x0080, 1, big_icon)
def BindJavascipt(): global browser jsBindings = cefpython.JavascriptBindings(bindToFrames=False, bindToPopups=True) jsBindings.SetProperty("currdir", GetParentPath("")) jsBindings.SetObject("app", JavascriptApp(browser)) browser.SetJavascriptBindings(jsBindings)
def OnLoadingStateChange(self, browser, is_loading, **_): """Called when the loading state has changed.""" try: if not is_loading: # Loading is complete def yield_transforms(transforms): self.browser_context.transforms = set(transforms) def yield_rects(rects): self.browser_context.rects = rects bindings = cef.JavascriptBindings(bindToFrames=False, bindToPopups=False) bindings.SetFunction("yieldTransforms", yield_transforms) bindings.SetFunction("yieldRects", yield_rects) browser.SetJavascriptBindings(bindings) with open(self.browser_context.kle_json_file, 'r', encoding='utf-8') as f: json = f.read() browser.ExecuteJavascript(r'''(function(){ window.deserializeAndRenderAndApply(''' + json + r'''); yieldTransforms(window.retrieveTransforms()); })(); ''') cef.PostDelayedTask(cef.TID_UI, 2000, wait_retrieve_transforms, self.browser_context, browser) except: import traceback print("[kle_scraper] ERROR: Failed in OnLoadingStateChange()") traceback.print_exc() cef.PostTask(cef.TID_UI, exit_scraping, browser)
def __init__(self, start_url, window_title="CEFApp", jinja_env=None, cef_temp_dir=None): """Initialize a new base CEF app :param start_url: Load url on browser startup :type start_url: str :param window_title: Top CEF browser title, defaults to "CEFApp" :type window_title: str, optional """ sys.excepthook = cef.ExceptHook cef.Initialize() self.jinja_env = jinja_env if cef_temp_dir is None: self.cef_temp_dir = os.path.join(os.path.dirname(__file__), ".cef_temp") else: self.cef_temp_dir = cef_temp_dir self.browser = cef.CreateBrowserSync(url=start_url, window_title=window_title) self.bindings = cef.JavascriptBindings(bindToFrames=False, bindToPopups=False) #Ajout des clients handler self.set_client_handlers()
def set_javascript_bindings(browser): external = External(browser) bindings = cef.JavascriptBindings(bindToFrames=False, bindToPopups=False) bindings.SetProperty("python_property", "This property was set in Python") bindings.SetFunction("html_to_data_uri", html_to_data_uri) bindings.SetObject("external", external) browser.SetJavascriptBindings(bindings)
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 set_javascript_bindings(browser): interface = CefAPI(browser) bindings = cef.JavascriptBindings() bindings.SetObject("python", interface) for name, value in interface.get_constants().items(): bindings.SetProperty(name, value) browser.SetJavascriptBindings(bindings)
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 embed_browser(self): window_info = cef.WindowInfo() (width, height) = self.GetClientSize() print("embed_browser0", width, height) if self.hidden: window_info.SetAsChild(self.Handle, [0, 0, 1, 1]) else: window_info.SetAsChild(self.Handle, [0, 0, width, height]) print("embed_browser", width, height) self.browser = cef.CreateBrowserSync(window_info, url=self.url) self.browser.SetClientHandler(FocusHandler(self)) self.browser.SetClientHandler(KeyboardHandler(self)) this = self def wx_fun(value): print("Value sent from Javascript: ", value) print(type(self)) #self.Show() bindings = cef.JavascriptBindings() bindings.SetFunction("wx_fun", wx_fun) self.browser.SetJavascriptBindings(bindings) if self.url: self.browser.GetMainFrame().LoadUrl(self.url) else: self.browser.GetMainFrame().LoadUrl("about:blank")
def on_after_create(browser, **_): cef.WindowUtils.SetTitle(browser, 'Kam1n0') bindings = cef.JavascriptBindings( bindToFrames=True, bindToPopups=False) bindings.SetObject("browser_controller", BrowserController(browser)) bindings.SetFunction("send_msg", send_msg) browser.SetJavascriptBindings(bindings)
def __init__(self, configPath): self.bindings = cef.JavascriptBindings(bindToFrames=False, bindToPopups=True) self.destSet = DestSet() self.dataTransfer = DataTransfer(self.destSet) with open(configPath, mode='r', encoding='utf-8') as f: data = json.load(f) self.reslove(data)
def bind(self): jsBindings = cefpython.JavascriptBindings(bindToFrames=True, bindToPopups=True) jsBindings.SetObject("localStorage", False) jsBindings.SetObject("Neexistujici", False) # jsBindings.SetObject("python", BindObject(self.browser)) self.browser.SetJavascriptBindings(jsBindings) self.browser.javascriptBindings.Rebind()
def set_javascript_bindings(uid): bindings = cef.JavascriptBindings(bindToFrames=False, bindToPopups=False) bindings.SetProperty("cefPython3", cef.GetVersion()) bindings.SetProperty('windowId', uid) bindings.SetProperty('system', platform.system()) bindings.SetProperty('systemLanguage', get_system_language()) bindings.SetObject('windowInstance', BrowserView.instances[uid]) BrowserView.instances[uid].view.SetJavascriptBindings(bindings)
def set_javascript_bindings(browser): #external = External(browser) bindings = cef.JavascriptBindings(bindToFrames=False, bindToPopups=False) #bindings.SetProperty("python_property", "This property was set in Python") #bindings.SetProperty("cefpython_version", cef.GetVersion()) bindings.SetFunction("py_print", py_print) #bindings.SetObject("external", external) browser.SetJavascriptBindings(bindings)
def prepare_browser(handler): cef.Initialize() browser = cef.CreateBrowserSync(url='http://' + host + ':' + str(port), window_title="NeuroNet") browser.SetClientHandler(LoadHandler()) bindings = cef.JavascriptBindings() bindings.SetFunction("py_function", handler) browser.SetJavascriptBindings(bindings) return browser
def initialize(self): self.task_thread = Thread(target=self.task, args=(self.task_q,)) self.task_thread.start() self.js_bindings = cefpython.JavascriptBindings(bindToFrames=False, bindToPopups=True) # in `html js` can call the function of js_func_name self.js_bindings.SetFunction('py_func', self.on_py_func) self.js_bindings.SetFunction('__py_cb', self.__py_sentinel) self.main_browser.SetJavascriptBindings(self.js_bindings)
def show_screen(file_name): browser = cef.CreateBrowserSync(url=endscreen_file_name, window_title="This should be borderless", settings=browser_settings) bindings = cef.JavascriptBindings(bindToFrames=True, bindToPopups=True) bindings.SetProperty("player_status", player_status) bindings.SetProperty("mission_status", mission_status) browser.SetJavascriptBindings(bindings) cef.MessageLoop()
def set_js_bindings(self): if not self._js_bindings: self._js_bindings = cef.JavascriptBindings(bindToFrames=True, bindToPopups=True) self._js_bindings.SetFunction("__kivy__request_keyboard", self.request_keyboard) self._js_bindings.SetFunction("__kivy__release_keyboard", self.release_keyboard) self.browser.SetJavascriptBindings(self._js_bindings)
def __init__(self, init_page='about:blank'): print("[CEFQtBackend] PyQt version: %s" % QtCore.PYQT_VERSION_STR) print("[CEFQtBackend] QtCore version: %s" % QtCore.qVersion()) CEFBackend.__init__(self) self.qt_app = _QtApp(sys.argv) self.mainWindow = MainWindow(url=init_page) self._jsBindings = cefpython.JavascriptBindings(bindToFrames=False, bindToPopups=True)
def set_javascript_bindings(browser): """set javascript bindings Arguments: browser {Browser} -- the google chrome handle """ bindings = cef.JavascriptBindings(bindToFrames=False, bindToPopups=False) pyapi = PyAPI(browser) bindings.SetObject("pyapi", pyapi) browser.SetJavascriptBindings(bindings)
def _bindJS(self): # Loads the javascript bindings bindings = cef.JavascriptBindings(bindToFrames=False, bindToPopups=False) for funcs in self.j_funcs: bindings.SetFunction(funcs["name"], funcs["function"]) for obj in self.j_obj: bindings.SetObject(funcs["name"], funcs["function"]) self.browser.SetJavascriptBindings(bindings)
def embed_browser(self): window_info = cef.WindowInfo() rect = [0, 0, self.winfo_width(), self.winfo_height()] window_info.SetAsChild(self.get_window_handle(), rect) self.browser = cef.CreateBrowserSync(window_info, url=self.url) bindings = cef.JavascriptBindings(bindToFrames=True, bindToPopups=True) bindings.SetFunction("alert", self.PyAlert) self.browser.SetJavascriptBindings(bindings) self.message_loop_work()
def __init__(self): cefpython.Initialize({ #"log_severity": cefpython.LOGSEVERITY_INFO, #"release_dcheck_enabled": False, # Enable only when debugging # This directories must be set on Linux "locales_dir_path": cefpython.GetModuleDirectory() + "/locales", "resources_dir_path": cefpython.GetModuleDirectory(), "browser_subprocess_path": "%s/%s" % (cefpython.GetModuleDirectory(), "subprocess"), }) self._cef_texture = Texture() self._cef_texture.set_compression(Texture.CMOff) self._cef_texture.set_component_type(Texture.TUnsignedByte) self._cef_texture.set_format(Texture.FRgba4) card_maker = CardMaker("browser2d") card_maker.set_frame(-self._UI_SCALE, self._UI_SCALE, -self._UI_SCALE, self._UI_SCALE) node = card_maker.generate() self._cef_node = render2d.attachNewNode(node) self._cef_node.set_texture(self._cef_texture) self._cef_node.set_transparency(TransparencyAttrib.MAlpha) winhnd = base.win.getWindowHandle().getIntHandle() wininfo = cefpython.WindowInfo() wininfo.SetAsOffscreen(winhnd) wininfo.SetTransparentPainting(True) self.browser = cefpython.CreateBrowserSync(wininfo, {}, navigateUrl='') self.browser.SetClientHandler( CefClientHandler(self.browser, self._cef_texture)) self._is_loaded = False self._js_onload_queue = [] self.browser.SetClientCallback("OnLoadEnd", self._load_end) self.jsbindings = cefpython.JavascriptBindings() self.browser.SetJavascriptBindings(self.jsbindings) self._js_func_queue = [] self._set_browser_size() base.accept('window-event', self._set_browser_size) base.buttonThrowers[0].node().setKeystrokeEvent('keystroke') base.accept('keystroke', self._handle_key) base.taskMgr.add(self._cef_message_loop, "CefMessageLoop") def shutdown_cef(): cefpython.Shutdown() atexit.register(shutdown_cef)
async def run_async(url, title="Pytigon", parent_win=None, x=200, y=200, width=1024, height=768): def py_function(value, js_callback): url = value[0] params = value[1] url2 = url.replace("file:///home/sch/prj/pytigon/pytigon", "http://127.0.0.2") print(url2, params) print("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA2") # print(url, url2) ret = request(url2 + "/", params) # print(ret.str()) print("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA3") # ret = "Hello world!" ret = ( """<base href="file:///home/sch/prj/pytigon/pytigon/" target="_blank">""" + ret.str()) ret = ret.replace( "window.BASE_PATH = '/'", "window.BASE_PATH = 'file:///home/sch/prj/pytigon/pytigon/'", ) js_callback.Call(ret, py_callback) def py_callback(value): print("Value sent from Javascript: " + value) browser, client_handler = create_browser(None, title, parent_win, x, y, width, height) bindings = cef.JavascriptBindings() bindings.SetFunction("py_function", py_function) bindings.SetFunction("py_callback", py_callback) browser.SetJavascriptBindings(bindings) for i in range(0, 10): cef.MessageLoopWork() await asyncio.sleep(0.01) browser.LoadUrl(url) async def loop(): nonlocal client_handler while not client_handler.close: cef.MessageLoopWork() await asyncio.sleep(0.01) await loop() del browser
def set_javascript_bindings(browser): bindings = cef.JavascriptBindings(bindToFrames=False, bindToPopups=False) # Binds connect four's functions to the application connect_four = ConnectFourGame(["Player One", "Minimax AI"]) bindings.SetObject('connectFour', connect_four) # Sets up AI ai = MinimaxAI(1, connect_four) bindings.SetObject('ai', ai) browser.SetJavascriptBindings(bindings)
def main(): cef.Initialize() browser = cef.CreateBrowserSync(url=cef.GetDataUrl(g_htmlcode), window_title="Javascript Bindings") browser.SetClientHandler(LoadHandler()) bindings = cef.JavascriptBindings() bindings.SetFunction("py_function", py_function) bindings.SetFunction("py_callback", py_callback) browser.SetJavascriptBindings(bindings) cef.MessageLoop() del browser cef.Shutdown()
def __init__(self, filepath=""): """ 构造函数 Args: filepath: 打开的文件路径 """ wx.Frame.__init__(self, parent=None, id=wx.ID_ANY, title='GitNote') # 初始化变量 self.dir = os.path.split(sys.argv[0])[0] if len(self.dir) == 0: self.dir = os.path.split(os.path.realpath(__file__))[0] # 加载图标 self.SetIcon(wx.Icon(os.path.join(self.dir, "res", "images", "gitnote.ico"), wx.BITMAP_TYPE_ICO)) # 窗口最大化 self.Maximize() # 初始化配置文件 self.config = self.InitConfig() # 初始化浏览器 cef.Initialize() wi = cef.WindowInfo() width, height = self.GetSize().Get() wi.SetAsChild(self.GetHandle(), [0, 0, width, height]) settings = { "web_security_disabled": True # 允许跨域请求 } self.browser = cef.CreateBrowserSync(wi, settings=settings) url = os.path.join(self.dir, "res", "html", "index.html") if len(filepath) == 0: url += "?showtree=1" self.browser.LoadUrl(url) js = cef.JavascriptBindings() box = mdbox.MDBox(self.config, filepath) js.SetObject('mdbox', box) self.browser.SetJavascriptBindings(js) print(dir(self.browser)) # 绑定事件 self.Bind(wx.EVT_CLOSE, self.OnClose) self.Bind(wx.EVT_SET_FOCUS, self.OnSetFocus) self.Bind(wx.EVT_SIZE, self.OnSize) self.Bind(wx.EVT_IDLE, self.OnIdle)
def run(self): logger.info('Running CEF window') original_excepthook, sys.excepthook = sys.excepthook, cef.ExceptHook try: self.init_window_dimensions() if IS_WINDOWS: logger.info('Enabling high DPI support for Windows') cef.DpiAware.EnableHighDpiSupport() logger.info('Initializing CEF window') cef.Initialize(**self.get_cef_initialize_kwargs()) window_info = cef.WindowInfo() window_info.SetAsChild( 0, [self.x_pos, self.y_pos, self.width, self.height]) self.browser = cef.CreateBrowserSync( window_title=self.WINDOW_TITLE, window_info=window_info, ) self.init_window() self.conf.register_on_update(self.on_conf_update) self.client_handler = ClientHandler(self) self.browser.SetClientHandler(self.client_handler) js_bindings = cef.JavascriptBindings() self.js_bridge = JSBridge(self) js_bindings.SetObject('__cefBridge', self.js_bridge) self.browser.SetJavascriptBindings(js_bindings) logger.info(f'Loading URL: {APP_URL}') self.browser.LoadUrl(APP_URL) cef.MessageLoop() logger.info('Shutting down') self.js_bridge._shutdown() cef.Shutdown() if self.client_handler._resource_handlers: logger.warn( f'{len(self.client_handler._resource_handlers)} ResourceHandlers exist, possible memleak!' ) finally: sys.excepthook = original_excepthook for dirname in ('blob_storage', 'webrtc_event_logs', 'webcache'): shutil.rmtree(dirname, ignore_errors=True)