I can access a Chrome App Webview HTML with:
webview.executeScript(
{code: 'document.documentElement.innerHTML'},
function(results) {
// results[0] would have the webview's innerHTML.
});
But I would like to get the value of global variables in the Guest like so:
webview.executeScript(
{code: 'window.globalVar'},
function(results) {
// results[0] should have the webview's value of "globalVar".
});
How can I do this?
An answer to summarize the steps required.
1) You inject a content script with
webview.executeScript()into the embedded page.2) Since the page's real
windowis isolated, you need a page-level script to access it. You inject it with a<script>tag as discussed here.3) The page-level script can access the
windowobject, but cannot talk to the app script. However, it can fire a custom DOM event, that the content script can catch. Discussed here.4) Finally, from the content script you need to send a message to your app script.
The content script callschrome.runtime.sendMessage, while the app script listens withchrome.runtime.onMessage.chrome.runtime.sendMessagedoes not seem to be available to webview content scripts injected withwebview.executeScript(). A workaround is to usepostMessageas described here.It's a bit of an onion structure, that's why you need 2 steps "in" and 2 steps "out". You can't really do it in the return value that's passed to the
executeScriptcallback, since at least one of the "out" steps will be asynchronous.