YosiFZ
YosiFZ

Reputation: 7890

Wpf WebBrowser load javascript

I have this WebBrowser in my page:

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

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);

And in MYSCRIPTCODE i have this function:

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.

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");

This line in the script get exception - Permission Denied:

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

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

Upvotes: 4

Views: 2836

Answers (1)

noseratio
noseratio

Reputation: 61656

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.

Upvotes: 3

Related Questions