Search code examples
microsoft-graph-apicross-site

Cross site issue with Microsoft Graph Toolkit


I'm following this tutorial to create a simple web app with a Microsoft 365 login. I'm currently getting this error when debugging locally (http://localhost:8080):

Warning:

mgt-loader.js:61 A parser-blocking, cross site (i.e. different eTLD+1) script, https://unpkg.com/@microsoft/mgt/dist/bundle/wc/webcomponents-loader.js, is invoked via document.write. The network request for this script MAY be blocked by the browser in this or a future page load due to poor network connectivity. If blocked in this page load, it will be confirmed in a subsequent console message. See https://www.chromestatus.com/feature/5718547946799104 for more details.

In Azure, I have the Redirect URIs set up to match (http://localhost:8080).

After some googling, I tried adding async, but then I get this warning and the login button doesn't appear:

mgt-loader.js:61 Failed to execute 'write' on 'Document': It isn't possible to write into a document from an asynchronously-loaded external script unless it is explicitly opened.

What would be causing this warning and how can I fix it?


Solution

  • First, check out how document.write works: https://developer.mozilla.org/en-US/docs/Web/API/Document/write

    You will understand why you cannot run document.write in asynchronous context (try running document.write('Hello world!'); in console on any page).

    Warning tells you that a parser blocking (synchronous), cross site (not coming from the same domain as website) scripts can be blocked by Chrome in the future if someone has unstable or bad internet connection.

    If you want it to run synchronously without that warning, you have to bundle that JS code with your own, or just serve it from your own origin, same as your website (e.g. localhost:8080). You can download @microsoft/mgt npm package and for bundling - use gulp, webpack or other tool of your choice.

    https://unpkg.com/@microsoft/[email protected]/dist/bundle/wc/webcomponents-loader.js

    This script tries to differentiate between async and sync contexts (line 175) and run document.appendChild (instead of write) for async context - but for some reason the check fails (readyState === loading).

    https://developer.mozilla.org/en-US/docs/Web/API/Document/readyState

    How to check if an Javascript script has been loaded Asynchronously (Async) or async attribute is present?

    If you want to run this in non-blocking manner, you could try to fix the script by yourself.

    There is a Github repo for that toolkit (https://www.npmjs.com/package/@microsoft/mgt), but there is no issue regarding async loading, nor regarding the warning that you have noticed - so maybe nobody else has noticed or thought about it yet.