Question

I'm trying to create a list of languages' directions (Left-To-Right or Right-To-Left. Other directions don't exist in Wikipedia) by their prefixes (en, fr, es, …) in Wikipedia. To do that I wrote a JS code that can be executed on this page and that stores the data in a variable. The code opens the main page of each Wikipedia and tries to check the direction of the language according to the 'dir' attribute of its <html> element. However, since each Wikipedia has a different domain, the browser won't let me access this data, for security reasons. Is there a browser that would? Is it possible to change my preferences to enable it?

P.S. The code:

var as = document.querySelectorAll('a.extiw'), pre, win, dirByPre = {};
for each (var a in as)
   if (pre = /^http:\/\/(\w+)\.wikipedia\.org\/wiki\/$/.exec(a.href)) {
      win = open(pre[0]);
      win.onload = function () {
         opener.dirByPre[pre[1]] = document.documentElement.dir;
         close();
      };
   }

Thanks a lot!

Was it helpful?

Solution

What you're running into is an Access Control Allow Origin error. Read up on it, Access Control Allow Origin not allowed by.

In general, if you want to access another page's data for use in JS, you need to do so on your own server and pass that to Javascript.

However, the best solution in this case is to instead access Wikipedia via its API and request a JSONP response. Remember, Wikipedia is built on MediaWiki, so see its API Docs http://www.mediawiki.org/wiki/API:Main_page.

title = "List_of_Wikipedias"; 

$.getJSON("http://en.wikipedia.org/w/api.php?action=query&prop=revisions&rvprop=content&titles="+title+"&format=json&callback=?", function(data) {
    console.log(data);
})

Note the "format=json" and the "callback=?"

This JSONP approach will work in all modern browsers.

OTHER TIPS

There is a reason that this is generally disallowed in modern browsers. There are many security issues that exist when arbitrary JavaScript is allowed to access other domains. A single example is XSS (cross-site scripting).

What you're trying to do would be much easier if you weren't trying to run your script inside the browser. Python, Ruby, or any other scripting language, really, could do this with ease using individual HTTP requests. And if you know JavaScript, how about Node.JS?

This might be an odd solution, but you could write a browser extension which would allow you to make cross domain requests. There are easy ways to develop extensions such as Crossrider which has an X-Domain addon that allows you to make cross domain requests via Javascript.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top