Thursday, January 12, 2023

workaround for same-origin-policy block for AJAX query to google apps script

https://www.labnol.org/code/20197-jquery-ajax-call-google-script

This post describes the exact problem and solution - the solution seems to be to use JSONP (JSON with padding) for the data, and then client page should read the JSON and appropriately display/use the data.

  • use a try catch in the Google Apps Script to prevent errors from preventing responses
  • convert to JSONP with
    result = JSON.stringify({
        result: result,
      });
    
      return ContentService.createTextOutput(e.parameter.callback + '(' + result + ')').setMimeType(
        ContentService.MimeType.JAVASCRIPT
      );
     
  • The AJAX query can be easily called with jQuery like
    var request = jQuery.ajax({
          crossDomain: true,
          url: url + encodeURIComponent(parameterIfAny),
          method: "GET",
          dataType: "jsonp"
        });
  • The script with jQuery must come after jQuery is included, like for example,
    <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
    </head>

No comments:

Post a Comment