문제

This is my GM_xmlhttpRequest script:

// ==UserScript==
// @name        test
// @namespace   test
// @include     http://stackoverflow.com/*
// @version     1
// ==/UserScript==

GM_xmlhttpRequest({
  method: "GET",
  url: "http://example.com",
  onload: function(response) {
    alert(response.responseText);
  }
});

function begin(){
    alert("ready");
}

$(document).ready(function() {
    begin();
}); 

Which alerts only the contents of example.com, not "ready".

BUT when I do the following nothing happens - there are no alerts whatsoever:

function begin(){
    GM_xmlhttpRequest({
      method: "GET",
      url: "http://example.com",
      onload: function(response) {
        alert(response.responseText);
      }
    });
    alert("ready");
}

$(document).ready(function() {
    begin();
}); 

What am I doing wrong?

도움이 되었습니까?

해결책

I'm pretty sure that the first example shows the contents returned by GM_xmlhttpRequest, but not the "ready"

jQuery/$ is not accessible directly within Greasemonkey. It's loaded inside the page(by stackoverflow.com in this case). To access functions/properties of the page you may use the unsafeWindow-object( http://wiki.greasespot.net/UnsafeWindow ):

unsafeWindow.$(document).ready(function() {
    begin();
}); 

But I would suggest to call begin() directly, you don't need $.ready() here, because GM-scripts will always execute when the DOMContentLoaded-event fires, which is equal to $.ready()

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top