Search code examples
javascripthtmljquerygoogle-apps-scriptgoogle-workspace

Problem loading external scripts like jQuery


I'm facing a problem since this morning with webapps deployed with Apps Script that used to works fine previously. Of course no changes has been made to justify this problem.

External scripts are not loaded from the HTML side, and a new error arise in the console.

In order to have a reproducible example:

Code.gs

function doGet() {

  var template = HtmlService.createTemplateFromFile('index');

  return template.evaluate()
                .setTitle('TEST')
                .addMetaTag('viewport', 'width=device-width, initial-scale=1')
                .setSandboxMode(HtmlService.SandboxMode.IFRAME)
}

index.html:

<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
  </head>
  <body>
        <div id="title">Hello</div>
  </body>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>

  <script>
    window.onload = function() {

      console.log('loaded');
      console.log($('#title').html());

    }
  </script>
</html>

Results in the console:

[ERROR] This document requires 'TrustedHTML' assignment. (jquery.min.js:2)

[ERROR] Uncaught TypeError: Failed to set the 'innerHTML' property on 'Element': This document requires 'TrustedHTML' assignment. (jquery.min.js:2)

[LOG] loaded

[ERROR] Uncaught ReferenceError: $ is not defined

The source problem appears to be the <script src='' loading jQuery. But I didn't notice any troubleshoot coming from Google, is it a new restriction for Apps Script?

Screenshots: projet/console

Error Sources

Network + CSP


Solution

  • As per the Google Issue Tracker, here's a workaround to put in the very top of your HTML <head>:

    <script>
      if (window.trustedTypes && window.trustedTypes.createPolicy) {
        window.trustedTypes.createPolicy('default', {
          createHTML: string => string,
          createScriptURL: string => string,
          createScript: string => string,
        });
      }
    </script>