問題描述
我剛剛開始使用 Electron,之前有使用 node-webkit (nw.js) 的經驗.
I'm just getting started with Electron, with prior experience with node-webkit (nw.js).
在 nw.js 中,我能夠創建 iframe,然后訪問所述 iframe 的 DOM,以獲取標題、favicon 等內容.幾天前,當我拿起 Electron 將我的 nw.js 應用程序移植到它時,我看到了使用 webviews 而不是 iframes 的建議,僅僅是因為它們更好.現在,我上面提到的功能在 nw.js 中相對容易實現,但我不知道如何在 Electron 中實現(示例很少).有人可以幫忙嗎?
In nw.js, I was able to create iframes and then access the DOM of said iframe in order to grab things like the title, favicon, &c. When I picked up Electron a few days ago to port my nw.js app to it, I saw advice to use webviews instead of iframes, simply because they were better. Now, the functionality I mentioned above was relatively easy to do in nw.js, but I don't know how to do it in Electron (and examples are slim to none). Can anyone help?
另外,我的 webview 有后退/前進按鈕(我打算有多個).我在文檔中看到我可以在 webview 上調用函數來執行此操作,但我嘗試過的也沒有任何效果(而且,我還沒有找到在野外使用它們的示例).
Also, I have back/forward buttons for my webview (and I intend on having more than one). I saw in the documentation that I could call functions for doing so on a webview, but nothing I have tried worked either (and, I haven't found examples of them being used in the wild).
推薦答案
除了 guest 以 NetOperatorWibby,從主人到客人也非常有用.目前唯一的方法是使用 <webview>.executeJavaScript(code, userGesture).這個 api 有點粗,但是可以.
Besides guest to host IPC calls as NetOperatorWibby, it is also very useful to go from host to guest. The only way to do this at present is to use the <webview>.executeJavaScript(code, userGesture). This api is a bit crude but it works.
如果您正在使用遠程訪客,例如擴展"第三方網頁,您還可以使用 webview preload 屬性,它會在頁面上運行任何其他腳本之前執行您的自定義腳本.請注意,出于安全原因,preload api 將在您的自定義腳本完成時核對在自定義 JS 文件的根命名空間中創建的任何函數,但是此托管過程不會核對您在根中聲明的任何對象.因此,如果您希望自定義函數保持不變,請將它們捆綁到一個單例對象中,您的自定義 API 將在頁面完全加載后保持不變.
If you are working with a remote guest, like "extending" a third party web page, you can also utilize webview preload attribute which executes your custom script before any other scripts are run on the page. Just note that the preload api, for security reasons, will nuke any functions that are created in the root namespace of your custom JS file when your custom script finishes, however this custodial process will not nuke any objects you declare in the root. So if you want your custom functions to persist, bundle them into a singleton object and your custom APIs will persist after the page fully loads.
[update] 這是一個我剛剛寫完的簡單示例:Electron-Webview-Host-to-Guest-RPC-Sample
[update] Here is a simple example that I just finished writing: Electron-Webview-Host-to-Guest-RPC-Sample
這篇關于如何訪問 <webview> 的 DOM在電子?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!