Greasy Fork is available in English.

Tartışmalar » Geliştirme

Fetching cross domain information synchronously

§
Gönderildi: 28.07.2019

Fetching cross domain information synchronously

Hi, I'm looking for proper use of GM_xmlhttpRequest, so that the script continues only after it's fully dispatched, ie. the onload function runs and finishes. I use Tampermonkey if it does matter.

woxxomMod
§
Gönderildi: 28.07.2019

Wrap it in a Promise, here's a bare bones example:

function gmGet(args) {
  return new Promise((resolve, reject) => {
    GM_xmlhttpRequest(
      Object.assign({
        method: 'GET',
      }, args.url ? args : {url: args}, {
        onload: e => resolve(e.response),
        onerror: reject,
        ontimeout: reject,
      })
    );
  });
}

Then use it with async/await syntax:

(async () => {
  const text = await gmGet('https://www.example.org/');
  const json = await gmGet({
    url: 'https://www.example.org/api.json',
    responseType: 'json',
  });
  // the data should be used inside this function, this is how asynchronous code works
})();

There are many existing wrappers that add more functionality/reliability.

§
Gönderildi: 13.12.2019
Düzenlendi: 31.12.2020

This is the only way it would work for me in Tampermonkey. (Don't forget to specify // @grant GM.xmlHttpRequest at the top of the script)

//Asynchronous cross-domain XHRs:
    var gmFetch = {} // https://www.vojtechruzicka.com/javascript-async-await/ AND https://gomakethings.com/promise-based-xhr/
    gmFetch.get = function (address,headers,anonymous) {
        return new Promise((resolve, reject) => {
            if (!headers){headers = ""}
            anonymous = anonymous ? anonymous : false;
            GM.xmlHttpRequest({
                method: "GET",
                url: address,
                headers: headers,
                anonymous: anonymous,
                onload: e => resolve(e.response),
                onerror: reject,
                ontimeout: reject,
            });
        });
    }
    gmFetch.post = function (address,postData,headers,anonymous) {
        return new Promise((resolve, reject) => {
            if (!headers){headers = {"Content-Type": "application/x-www-form-urlencoded"}}
            anonymous = anonymous ? anonymous : false;
            GM.xmlHttpRequest({
                method: "POST",
                url: address,
                headers: headers,
                data: postData,
                anonymous: anonymous,
                onload: e => resolve(e.response),
                onerror: reject,
                ontimeout: reject,
            });
        });
    }
    async function testFetch() {
        try {
            const result = await gmFetch.get("http://textfiles.com");
            console.log(result);
        } catch (error) {
            // Error handling
            console.log(error);
        } finally {
            // After try/catch is done,
            // do this whether there was error or not
            console.log("request finished")
        }
    }
    testFetch();

Cevap paylaş

Yanıt göndermek için oturum açın.