1

I am trying to write a userscript that (should) allow me to open a translator from any web page.

I append a button to the body of current web page, when clicking on it, it retrieve content from a translator (google, reverso...) and display it on the web page.

Here is the code:

var input = document.createElement("input");
input.type = "button";
input.value = "Open translator";
input.onclick  = OpenTranslator;

document.body.appendChild(input);

function OpenTranslator(){
  GetTranslatorContent();
}

function GetTranslatorContent(){
  $.get('http://www.reverso.net/text_translation.aspx?lang=FR').then(function(responseData){
    //alert("Got content");
    //document.body.appendChild($('.translate-holder'));
    var targetContent = $('.translate-holder');
    if (targetContent != null && targetContent != undefined){
      alert("Good so far");
    }
  })

}

However, I got this message when running this code:

Error from previous code

So, my question is the folowing:

Is it possible to do what I am trying to do? (get content from a page to put it in an other)

If the answer to the previous question is yes, I am able to do so on pages I am not the admin? (because if I understood well, the error I get is caused because the page I am requesting is not allowing me to do what I want)

Thanks

Itération 122442
  • 2,644
  • 2
  • 27
  • 73

1 Answers1

2

Yep it's possible. You have to use cross domain requests. Look an example on pure JS.

var XHR = ("onload" in new XMLHttpRequest()) ? XMLHttpRequest : XDomainRequest;

var xhr = new XHR();

// cross domain request
xhr.open('GET', 'http://domain/request', true);

xhr.onload = function() {
  alert( this.responseText ); // response
}

xhr.onerror = function() {
  alert( 'Error ' + this.status ); // Error
}

xhr.send();

But don't forget that:

Regular web pages can use the XMLHttpRequest object to send and receive data from remote servers, but they're limited by the same origin policy. Extensions aren't so limited. An extension can talk to remote servers outside of its origin, as long as it first requests cross-origin permissions.

(from https://developer.chrome.com/apps/xhr)

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
zhuravlyov
  • 503
  • 2
  • 11