SeanM
SeanM

Reputation: 53

Userscript (Javascript): How to handle an asynchronous callback from Google Apps Script

Edit: This is my fourth attempt at rewording my question to come to a desired solution. I apologize for my lack of clarity.

I have a Tampermonkey userscript that helps me send data to a Google Sheets database.

The userscript creates a hyperlink on the webpage it is running on, and when I want to send data to the database, I click on the hyperlink which will open in a new tab:

<a href='https://script.google.com/macros/s/XXXXXXXXXXXX/exec?data1=data' target='_blank'>Click here for a new tab</a>

My Google script handles the request and returns an asynchronous callback result through this process:

return ContentService
  .createTextOutput(e.parameter.callback+"("+ output + ");")
  .setMimeType(ContentService.MimeType.JAVASCRIPT);

The new tab will redirect to "https://script.googleusercontent.com/macros/echo?user_content_key=XXXXXXXXXXXX" in my browser and display either of these two results that are returned:

{"result":"success"}

or

{"result":"duplicate"}

Depending on the result, I will manually do something.

I am looking for a way to handle the asynchronous callback from the Google Script within my userscript so that I no longer have to manually perform an action. I have not yet figured out how to handle asynchronous requests within the userscript.

Would someone please provide me with some code for the userscript that will handle the asynchronous callback and log the result via console.log()?

Any help is appreciated. Thank you!

Upvotes: 2

Views: 289

Answers (1)

SeanM
SeanM

Reputation: 53

I finally was able to log a result through console.log with the help from another SO question.

function getLink (url) {
GM_xmlhttpRequest ( {
    method: 'GET',
    url: url,
    onload: function (response) {
        var resp = response.responseText;
        console.log (resp);
        // DO EVERYTHING THAT REQUIRES resp HERE.
    }
} );
}

Also, I had to add the following to my userscript:

// @grant       GM_xmlhttpRequest

Upvotes: 1

Related Questions