How to load the google maps api via a userscript / synchronously?

GJ. picture GJ. · May 4, 2014 · Viewed 12.8k times · Source

I'm writing a userscript (greasemonkey script) that needs to add a google map to a page on a website that I don't control.

I tried to add the script like so (which works well when loading other scripts that I tried) :

var my_script = document.createElement('script');
my_script.setAttribute('src',
             'https://maps.googleapis.com/maps/api/js?key=API_KEY&sensor=false');
document.head.appendChild(my_script);

But this fails with:

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.

How can I load and use the maps api from a userscript?

Answer

DoubleU23 picture DoubleU23 · Jul 22, 2014

according to the docs it's only possible to load the API per script
unless you provide the parameter callback
=> load Google Maps API asynchronously

I don't have any experience in writing userscripts but i hope it helps.

ATTENTION: Don't forget to add the callback function into the global namespace.
(In plain JS you would add it to the window object.)