What is cross-origin? Why do we write cross-origin in our code?

zeeshansafdar48

Zeeshan Safdar

Posted on June 3, 2023

What is cross-origin? Why do we write cross-origin in our code?

In web development, the term "cross-origin" refers to interactions between web pages or scripts that originate from different domains, protocols, or ports. Browsers enforce a security policy called the "same-origin policy" that restricts these interactions by default. The policy aims to prevent malicious websites from accessing or manipulating data from other websites without explicit permission.

Example

<script crossorigin src="https://unpkg.com/react@18/umd/react.development.js"></script>

The crossorigin attribute I included in my code snippet is used when loading external resources, such as scripts, stylesheets, or images, from a different origin. It is primarily used for loading resources that support Cross-Origin Resource Sharing (CORS).

When I set the crossorigin attribute to a value, such as "anonymous" or "use-credentials," I indicate to the browser how it should handle any cross-origin requests made while fetching the resource.

In my example, By including the crossorigin attribute, I am specifying that the browser should handle any cross-origin requests made by this script according to the CORS policy. This can include making AJAX requests to other domains or loading additional resources like stylesheets or images.

It's important to note that the use of the crossorigin attribute depends on the specific resource being loaded and whether the server hosting the resource supports CORS headers. If the server does not send the necessary CORS headers, the crossorigin attribute may not have any effect.

To fully understand the concept of CORS, let's have a look into it in detail.

💖 💪 🙅 🚩
zeeshansafdar48
Zeeshan Safdar

Posted on June 3, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related