我可以通过以下方式访问 Chrome 应用程序 Webview HTML:
webview.executeScript(
{code: 'document.documentElement.innerHTML'},
function(results) {
// results[0] would have the webview's innerHTML.
});
但我想像这样获取 Guest 中全局变量的值:
webview.executeScript(
{code: 'window.globalVar'},
function(results) {
// results[0] should have the webview's value of "globalVar".
});
我怎样才能做到这一点?
总结所需步骤的答案。
1)您注入一个内容脚本webview.executeScript()
进入嵌入页面。
2)由于页面是真实的window
是孤立的,你需要一个页面级脚本来访问它。你用一个注入它<script>
所讨论的标签here https://stackoverflow.com/questions/9515704/building-a-chrome-extension-inject-code-in-a-page-using-a-content-script.
3)页面级脚本可以访问window
对象,但无法与应用程序脚本对话。但是,它可以触发内容脚本可以捕获的自定义 DOM 事件。讨论过here https://stackoverflow.com/a/26740141/934239.
4) Finally, from the content script you need to send a message to your app script. The content script calls chrome.runtime.sendMessage
, while the app script listens with chrome.runtime.onMessage
. chrome.runtime.sendMessage
does not seem to be available to webview content scripts injected with webview.executeScript()
. A workaround is to use postMessage
as described here https://stackoverflow.com/q/30367455/934239.
它有点像洋葱结构,这就是为什么你需要 2 步“进”和 2 步“出”。您实际上无法在传递给的返回值中执行此操作executeScript
回调,因为至少其中一个“out”步骤将是异步的。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)