Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

(Unknown): Script Error in JavaScript

DZone 's Guide to

(Unknown): Script Error in JavaScript

Have ever tried to run your code only to see, 'Script error.' Super annoying. Read on to learn how to debug your JS code!

· Web Dev Zone ·
Free Resource

If someone tries to violate the rule that you have set, what do you do in return? Send them an Script error.

Not in real life, though. 

But in JavaScript, if you try to violate the same origin policy, the browser will send you a 'Script error' in return.

(Unknown) Script Error in JavaScript

When Do Script Error Occur in JavaScript Code?

When an exception violates the same origin policy of a browser in response to the onerror callback, the browser responds with a 'script error.'

Same Origin Policy: According to the same origin policy, the browser accepts only the scripts hosted on the same server on two different web pages.

Every browser has a set of acceptable or required 'Request Headers.' When you hit any request on the server, it should contain those essentials for the request header. Otherwise, you are going to face a script error.

Well, this is an intentional behavior by the browsers in order to prevent scripts from leaking to external domains, as no one wants to entertain unwanted requests.

I Am Facing a Script Error in JavaScript, What Should I Do?

If you also face the same issue, then go ahead with these possible solutions.

1. Set Up a Cross-Origin HTTP Header

Access-Control-Allow-Origin: *

By setting Access-Control-Allow-Origin: to * , you make sure that you can access the resource from any domain. If necessary, you can also replace the * with the specific domain name that you want to access your domain’s script.

There is a different method to set this to * in different environments.

  • Apache: Create an .htaccess file in the folder where your JS file is served with:
Header add Access-Control-Allow-Origin "*"
  • Nginx: Add the add_header directive: 

location ~ ^/assets/ {
    add_header Access-Control-Allow-Origin *;
}
  • HA Proxy: Add this asset: 

rspadd Access-Control-Allow-Origin:\ *

2. Set crossorigin=”anonymous”

For every script in your HTML script, that you’ve set Access-Control-Allow-Origin, set crossorigin="anonymous"

<script src="http://another-domain.com/app.js" crossorigin="anonymous"></script>

This code tells that your browser to fetch the target file anonymously avoiding transmission of any user identifying information like HTTP credentials or cookies while requesting by the browser.

If you face any script error in your JavaScript code, hope this article may prove to be of help.

Topics:
javascript ,web dev ,javascript tutorial ,debugging javascript

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}