开发者

Why am I getting null value when trying to use the mediawiki api from a chrome extension js script?

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?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜