GJ.
GJ.

Reputation: 5364

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

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?

Upvotes: 13

Views: 13226

Answers (3)

Gonzalo
Gonzalo

Reputation: 882

You have to add a callback function to the script loading. If you are using it in phonegap, you should check internet connection, and also if it is already loaded. Yuo can ask and I will give you the piece of code.

<!DOCTYPE html>
<html>
  <head>
    <title>Asynchronous Loading</title>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <style>
      html, body, #map-canvas {
        height: 100%;
        margin: 0px;
        padding: 0px
      }
    </style>
    <script>
function initialize() {
  var mapOptions = {
    zoom: 8,
    center: new google.maps.LatLng(-34.397, 150.644)
  };

  var map = new google.maps.Map(document.getElementById('map-canvas'),
      mapOptions);
}

function loadScript() {
  var script = document.createElement('script');
  script.type = 'text/javascript';
  script.src = 'https://maps.googleapis.com/maps/api/js?v=3.exp&' +
      'callback=initialize';
  document.body.appendChild(script);
}

window.onload = loadScript;

    </script>
  </head>
  <body>
    <div id="map-canvas"></div>
  </body>
</html>

Upvotes: 2

DoubleU23
DoubleU23

Reputation: 118

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.)

Upvotes: 6

abmd
abmd

Reputation: 301

you may try adding an 'async' attribute to my_script, like this:

my_script.setAttribute('async',true);

Also you can look this: https://developers.google.com/maps/documentation/javascript/tutorial?hl=en#asynch

Upvotes: 0

Related Questions