I want to do some AJAX operations in my Tampermonkey script, and I find jQuery rather convenient. Is it still currently the case that there is no way to get jQuery AJAX to work with Tampermonkey?

Please note that the operations will not be to the same origin, which is the whole reason to use Tampermonkey. Greasemonkey is OK too.

有帮助吗?

解决方案

jQuery AJAX works fine with Tampermonkey and Greasemonkey, with only one limitation compared to jQuery use in a web page.

For example, this cross-origin script works in both Tampermonkey and Greasemonkey:

// ==UserScript==
// @name     _Demonstrate jQuery AJAX from Tampermonkey
// @include  https://stackoverflow.com/questions/18546180/*
// @require  http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js
// @grant    GM_addStyle
// ==/UserScript==
/*- The @grant directive is needed to work around a design change
    introduced in GM 1.0.   It restores the sandbox.
*/
$.ajax ( {
    type:       'GET',
    url:        'https://api.stackexchange.com/2.1/users/621338?site=stackoverflow&filter=!)2R0ltXnW6.fyPDiHJm',
    dataType:   'JSON',
    success:    function (apiJson) {
        var resultObj = apiJson.items[0];
        alert (
              'User ' + resultObj.display_name
            + ' has accept rate of ' + resultObj.accept_rate + '%.'
        );
    }
} );



Important:

  1. The target URL must be same domain, or the target server must have appropriate CORS values set.

    For servers that are not cross-domain friendly, you must use GM_xmlhttpRequest()Doc for your AJAX.

  2. JSONP is a special case due to sandbox and scope issues.
    Avoid JSONP, or use this approach, or ask a new question for a specific problem.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top