WPF web浏览器的JavaScript加载 [英] Wpf WebBrowser load javascript

查看:147
本文介绍了WPF web浏览器的JavaScript加载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的 web浏览器在我的网页:

I have this WebBrowser in my page:

<WebBrowser HorizontalAlignment="Stretch" Name="Browser"
            VerticalAlignment="Stretch" Grid.Column="1"/>

现在后,我加载一个网页,我想注入的JavaScript code有:

Now after i load a page i want to inject a JavaScript code with :

var doc = (HTMLDocument)Browser.Document;
var head = doc.getElementsByTagName("head").Cast<HTMLHeadElement>().First();
var script = (IHTMLScriptElement)doc.createElement("script");
script.text = MYSCRIPTCODE;
head.appendChild((IHTMLDOMNode)script);

而在 MYSCRIPT code 我有这个功能:

function checkSomething() {

    try{
           var xhr = new XMLHttpRequest();
           var url = 'weburl';
           xhr.open("GET", url, true);
           xhr.onreadystatechange = function () {
           //Somecode
           }

           xhr.send();
    } catch {

    }
}

和我一起运行它:

And i run it with:

Browser.InvokeScript("checkSomething");

这是工作完美,没有任何问题,运行脚本。

It's work perfect and run the script without any problem.

我有另一种状态,我加载本地HTML文件,浏览器:

I have another state that i load local html file to the browser:

Uri uri = new Uri(AppDomain.CurrentDomain.BaseDirectory + @"OfflinePage.html");
Browser.Navigate(uri);

而当我想以运行它:

And when i want to run it with :

Browser.InvokeScript("checkSomething");

这行脚本的GET例外 - 被拒绝的权限:

This line in the script get exception - Permission Denied:

xhr.open("GET", url, true);

为什么发生任何想法?为什么它在一个页面,我从网页加载工作,而不会在一个地方的HTML工作?

Any idea why it happen? why it work in a page that i load from web and won't work in a local html?

推荐答案

您最初的页面 OfflinePage.html 来自本地文件系统,而你的XHR网址是网页地址。 web浏览器禁止这是一个跨域安全限制。您可以使用 XDomainRequest 以解决这个问题,但在Web服务器应该给予明确同意跨域请求通过包括访问控制 - 允许 - 产地:响应* HTTP标头。在HTTP访问控制(CORS)更多信息这里

Your initial page OfflinePage.html comes from the local file system, while your XHR URL is a web address. WebBrowser prohibits this as a cross-domain security restriction. You can use XDomainRequest to solve the problem, but the web server should give explicit consent to cross-domain requests by including Access-Control-Allow-Origin: * HTTP header in response. More info on HTTP Access Control (CORS) here.

这篇关于WPF web浏览器的JavaScript加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆