2

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?

4

2 回答 2

5

您可以从被调用的脚本中获取返回值,但您必须向从 invokeScriptAsync 返回的对象添加一个完整的处理程序。以HTML Webview 控件示例的场景 5 为例,修改 5_InvokeScript.js 中的代码如下:

function invokeScript() {
    var op = document.getElementById("webview").invokeScriptAsync("changeText", document.getElementById("textInput").value);

    op.oncomplete = function (e) {
        console.log(e.target.result);
    };

    op.start();
}

然后在 script_example.html 中,将函数更改为:

function changeText(text) {
    document.getElementById("myDiv").innerText = text;
    return text;
}

在应用程序中的 console.log 调用上设置断点,您将看到 e.target.result 包含返回值。

window.external.notify也可以,MSWebViewScriptNotify从 Webview 引发事件。请注意,这MSWebViewScriptNotify只会从加载了 ms-appx-web、ms-local-stream 和 https 内容的 webview 中引发,其中 https 还需要您的清单中的内容 URI 规则,否则该事件将被阻止。如果您涉及 URI 解析器,也允许使用 ms-appdata。通过 navigateToString 加载的 webview 没有这个要求。

于 2013-11-01T21:17:14.220 回答
1

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.

于 2013-11-07T08:47:51.430 回答