问题
I am developing a Windows Store HTML5/Javascript app. As part of my app I need to invoke a Javascript method on a web page and retrieve its return value.
The control x-ms-webview
has a method invokeScriptAsync
that can invoke a script on a webview. However there is no way of retrieving a value back from any method call.
It also does not seem to support the standard method of communication with a host app, window.external.notify
.
How can I retrieve a value from a web page in a Windows Store app webview?
回答1:
You can get return values from an invoked script, but you have to add an oncomplete handler to the object returned from invokeScriptAsync. For example, take scenario 5 of the HTML Webview control sample and modify the code in 5_InvokeScript.js as follows:
function invokeScript() {
var op = document.getElementById("webview").invokeScriptAsync("changeText", document.getElementById("textInput").value);
op.oncomplete = function (e) {
console.log(e.target.result);
};
op.start();
}
And then in script_example.html, change the function to this:
function changeText(text) {
document.getElementById("myDiv").innerText = text;
return text;
}
Set a breakpoint on the console.log call in the app and you'll see that e.target.result contains the return value.
window.external.notify
does also work, raising the MSWebViewScriptNotify
event from the Webview. Note that MSWebViewScriptNotify
will be raised only from webviews loaded with ms-appx-web, ms-local-stream, and https content, where https also requires a content URI rule in your manifest, otherwise that event will be blocked. ms-appdata is also allowed if you have a URI resolver involved. A webview loaded through navigateToString does not have this requirement.
回答2:
RIGHT.
Starting to make a bit more sense. The code I mentioned in the comments:
var async = webview.invokeScriptAsync('eval', '(function() { return 1337 })()')
async.oncomplete = function(e) {
console.log(e.target.result)
}
async.start()
logs null.
However replacing the number 1337
with the string '1337'
logs the expected value.
Still no luck with doing window.external.notify
-- but at least some form of dialogue with the webview is possible.
EDIT window.external.notify
does work, this answer originally had the wrong event to listen for, but it is now correct.
来源:https://stackoverflow.com/questions/19734973/retrieving-data-from-webview-in-windows-8-1-store-html5-app