Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Some JS scripts loading in Chrome but not in Firefox

I am having some odd issues with some external scripts on my website. I finally got it down to this snippet.

<script type="text/javascript" src="//www.googleadservices.com/pagead/conversion.js" onload="console.log('conversion')"></script>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" onload="console.log('jquery')"></script>

Loading this in firefox has just the second script loading, while with chrome, both load. This is on OSX with the latest browsers.

Now if I add the crossorigin attribute to both scripts, then it stops working in chrome with this error Script from origin 'http://www.googleadservices.com' has been blocked from loading by Cross-Origin Resource Sharing policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://www.example.com:3000' is therefore not allowed access.

The scripts now are

<script type="text/javascript" src="//www.googleadservices.com/pagead/conversion.js" onload="console.log('12123')" crossorigin async></script>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" onload="console.log('123')" async crossorigin></script>

I was struck by this difference in behaviour. Is this due to firefox being more strict than CHrome? Is this a setting I set somewhere? Or is this a bug on Firefox/Chrome's side?

Also, should I talk to the vendor to get their js setup for CORS? What struck me was that google was failing, but I have another resource breaking as well.

By right MDN claims that script tags are not limited by the same origin policy.

like image 231
Karthik T Avatar asked Feb 12 '16 09:02

Karthik T


1 Answers

The Cross-Origin Resource Sharing policy exists to prevent Site A from taking scripts or data hosted on Site B, and including them on it's own site. If Site A wants to allow Site B to access those scripts, they can set an Access-Control-Allow-Origin header. This header means that Site B can allow specified hosts to include the scripts on their site.

Site B needs to enable the Access-Control-Allow-Origin header on their server, to allow you to access it. For a single url, set the following header:

Access-Control-Allow-Origin: http://yoursite.com

Edit

The crossorigin attribute does not allow different origins to use the script, it just handles the window.onerror differently. From the MDN Page:

Normal script elements pass minimal information to the window.onerror for scripts which do not pass the standard CORS checks. To allow error logging for sites which use a separate domain for static media, several browsers have enabled the crossorigin attribute for scripts using the same definition as the standard img crossorigin attribute. Efforts to standardize this attribute are underway on the WHATWG mailing list.

like image 101
IeuanG Avatar answered Oct 18 '22 14:10

IeuanG