简体   繁体   English

Windows 10 WebView InvokeScript无法正常工作

[英]Windows 10 WebView InvokeScript Not Working

My Windows 10 universal app is using a webview that uses InvokeScript to call the JS function "eval" while injecting some other javascript into the function. 我的Windows 10通用应用程序正在使用一个Web视图,该Web视图使用InvokeScript调用JS函数“ eval”,同时向该函数中注入其他一些JavaScript。 However, when I test it out, nothing happens. 但是,当我进行测试时,什么也没有发生。 Debugging shows that the script is being stored correctly and it is hitting the function, but the webview doesn't seem to update at all. 调试显示脚本已正确存储并且正在运行该功能,但Webview似乎根本没有更新。

private void browser1_LoadCompleted_1(object sender, NavigationEventArgs e)
    {
        try
        {
            count++;
            browser1.InvokeScript("eval", test);
        }
        catch (Exception E)
        {

        }

        address.Text = browser1.Source.ToString();
    }
}

This code worked perfectly on Windows Phone 8 and earlier. 此代码在Windows Phone 8和更早版本上可以完美运行。 But now with the Windows 10 webview, it seems to have no effect. 但是现在使用Windows 10 Webview似乎没有效果。 This is the code for storing my script in the test variable: 这是用于将脚本存储在测试变量中的代码:

private async void ReadFile()
    {
        string fileContent;
        StorageFile file = await StorageFile.GetFileFromApplicationUriAsync(new Uri(@"ms-appx:///Script.js"));
        using (StreamReader sRead = new StreamReader(await file.OpenStreamForReadAsync()))
            fileContent = await sRead.ReadToEndAsync();
        test = new string[] { fileContent };
    }

I'm not sure why nothing happens. 我不确定为什么什么也没发生。 I've confirmed the test variable does indeed contain the script when InvokeScript is called. 我已经确认调用InvokeScript时测试变量确实包含脚本。 I've even tested the InvokeScript with different and simpler JS scripts that definitely worked in the Windows Phone 8 version of this app. 我什至用不同且更简单的JS脚本测试了InvokeScript,这些脚本肯定可以在此应用程序的Windows Phone 8版本中使用。 Is there something I'm missing to get the webview to update when the JS function is invoked? 调用JS函数时,我是否缺少使Web视图更新的功能?

Turns out the solution was quite simple. 事实证明,解决方案非常简单。 Apparently InvokeScript has been deprecated in Windows 10 UWP and only InvokeScriptAsync works now. 显然,InvokeScript在Windows 10 UWP中已被弃用,并且只有InvokeScriptAsync现在可以使用。 So all I had to do is make my method an async method and then await the InvokeScriptAsync call. 因此,我要做的就是使我的方法成为异步方法,然后等待InvokeScriptAsync调用。

InvokeScript in Windows 10 only works with trusted source. Windows 10中的InvokeScript仅适用于受信任的源。 I have tried and got the same result as you. 我已经尝试过并得到与您相同的结果。 The exact script worked before on Win 8 no longer work on UWP. 在Win 8上运行过的确切脚本不再在UWP上运行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM