0

Why I get a CORS error:

Access to script at 'https://maps.googleapis.com/maps/api/js' from origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

When I try to import dynamically Google Maps API in my JavaScript:

  await import('https://maps.googleapis.com/maps/api/js')

But not when I do it in my HTML:

  <script defer src="https://maps.googleapis.com/maps/api/js"></script>

Any idea would be really appreciate it.

Note: if I import other URL libraries I don't have problems, ex: hammer.js cdn

async function init_map() {
  await import('https://maps.googleapis.com/maps/api/js')
}

init_map()
Johnny Johnny
  • 319
  • 2
  • 11
  • 1
    What does the error you get say? Perhaps google doesn't set the CORS permissions to allow it, while the other ones do – geocodezip Jun 04 '20 at 23:19
  • Thank you so much @geocodezip for your answer : ), I have updated the post with the CORS error: has been blocked by CORS policy... – Johnny Johnny Jun 05 '20 at 09:46
  • but if google doesn't allow it why I'm able to do it in the HTML? – Johnny Johnny Jun 05 '20 at 09:49
  • 2
    This is basically what I explained to you yesterday. Some endpoints allow cross-origin requests, some don't. Google doesn't, at least for the Maps API. Here is some more info: https://stackoverflow.com/questions/50097327/using-a-full-url-in-a-dynamic-import – MrUpsidown Jun 05 '20 at 11:29
  • @MrUpsidown you are back, thanks! it says "web browsers do implement dynamic loading over HTTP" So, Google allows me to use Google Maps API if I import it in HTML tag but not in JavaScript. What's the different how they know it? – Johnny Johnny Jun 05 '20 at 12:00
  • 2
    Browsers don't check the CORS policy for loading with script tags, they do for dynamic loading. – geocodezip Jun 05 '20 at 14:12
  • Now everything is totally clear @geocodezip that was the thing I was missing! Thanks a lot, I'm a newbie – Johnny Johnny Jun 05 '20 at 15:15

1 Answers1

0

I found asolution. But I am not sure if this is working everywhere.

At least it is working on current Chrome, Firefox and Edge Browser.

var url = "https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true&libraries=places&key=" + gkey;
$(document.head).append($('<script>', { src: url }));
Philipp S.
  • 827
  • 17
  • 41