javascriptgreasemonkeygreasemonkey-4

GM.xmlHttpRequest `synchronous` option not working


The following code creates an alert with the content undefined:

// ==UserScript==
// @name     Unnamed Script 188765
// @version  1
// @grant    GM.xmlHttpRequest
// @include  http*//markasoftware.com/*
// ==/UserScript==

alert(typeof GM.xmlHttpRequest({
  url: 'https://google.com',
  synchronous: true,
  method: 'GET',
}));

Based on the documentation, I would expect the synchronous option to make the call return a response object. Yet, it acts the same way as an async call would; the onload handler still works. Was the synchronous option disabled? Is there some other way to make a cross-origin request synchronously?


Solution

  • The documentation that says that the return value will be different when using synchronous mode is wrong. Just set a variable that you use outside of the onload function.

    let returnData;
    GM.xmlHttpRequest({
      url: 'https://google.com',
      synchronous: true,
      method: 'GET',
      onload: function(response) {
        returnData = response;
      }
    }));
    alert(returnData);