views:

25

answers:

1

I have a javascript script in a chrome extension i'm building. It is content script.

The script is using mediawiki api:

function wikifind(str)
{
    var req = new XMLHttpRequest();
    url = "http://en.wikipedia.org/w/api.php?action=query&format=xml&titles="+str;
    req.open("GET", url, true);
    req.send;
}    

I have two questions.

First There is the event of the response. not sure where I'm supposed to put it.

req.onreadystatechange=function()
{
    if (req.readyState==4 && req.status==200)
    {
        document.write(req.responseXML);
    }
}

Somewhere after the function that sends the request, inside it or otherwise?

Second more important question/problem is that when I try to access the response I get null value.

I tried to switch the format to JSON as was said in a similar question, but that didn't work. Also tried synchronous requests, but still getting null value.

Any ideas? Does this have anything to do with security limitations of extensions, or just problems with my code?

+1  A: 

This looks like a same-origin problem to me. As per the documentation, cross-domain XHR is not supported from content scripts. Users are recommended to create a background page, declare cross-origin permissions to the site in question (in this case http://en.wikipedia.org) in the manifest and then communicate between the content script and the background page using message passing.

An example of this technique (with source code) is available.

npdoty
Yes you're right. I changed it to work from the background.html and exchange messages with the code and it works. Thanks
Uri