search
HomeWeb Front-endFront-end Q&AWhat is the same origin policy in javascript

What is the same origin policy in javascript

Jan 26, 2022 pm 02:14 PM
javascriptSame origin policy

In JavaScript, the same-origin policy is an important security metric for client-side scripts (especially Javascript). That is, two pages with the same protocol (protocol), port, and host (domain name) belong to same source.

What is the same origin policy in javascript

The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.

What is the same-origin policy?

The Same Origin Policy is an important security metric for client-side scripts (especially Javascript). It first came out of Netscape Navigator 2.0, and its purpose was to prevent a document or script from being loaded from multiple different sources.

Same-origin policy means that two pages with the same protocol, port (if specified), and host (domain name) belong to the same source.

For example, http://www.example.com/dir/page.htmlThis URL,
protocol is http://,
domain name is www .example.com,
The port is 80 (the default port can be omitted). Its homology is as follows.

    http://www.example.com/dir2/other.html:同源
    http://example.com/dir/other.html:不同源(域名不同)
    http://v2.www.example.com/dir/other.html:不同源(域名不同)
    http://www.example.com:81/dir/other.html:不同源(端口不同)

Essence:

The essence is simple: it considers trusted content loaded from any site to be unsafe. When scripts that are mistrusted by the browser are run in a sandbox, they should only be allowed to access resources from the same site, not those from other sites that may be malicious.

Why is there a same-origin restriction?

Let’s give an example: For example, a hacker program uses IFrame to embed the real bank login page on his page. When you log in with your real username and password, his page will The content of the input in your form can be read through Javascript, so that the username and password can be easily obtained.

The purpose of the same origin policy is to ensure the security of user information and prevent malicious websites from stealing data.

Imagine a situation like this: Website A is a bank. After the user logs in, he browses other websites. What happens if other websites can read website A’s cookies?

Obviously, if the cookie contains privacy (such as the total deposit amount), this information will be leaked. What's even more frightening is that cookies are often used to save the user's login status. If the user does not log out, other websites can impersonate the user and do whatever they want. Because the browser also stipulates that submitting forms is not restricted by the same-origin policy.

It can be seen that the "same origin policy" is necessary, otherwise cookies can be shared and the Internet will be unsafe at all.

Restriction scope

With the development of the Internet, the "same origin policy" is becoming more and more strict. Currently, there are three behaviors that are restricted if they are not of the same origin.

(1) Cookie、LocalStorage 和 IndexDB 无法读取。

(2) DOM 无法获得。

(3) Ajax 请求不能发送。

Although these restrictions are necessary, they are sometimes inconvenient and affect reasonable purposes. Below, I will introduce in detail how to circumvent the above three limitations.

Avoidance method

1. Cookie

#Cookie is a piece of information written by the server to the browser. Small pieces of information can only be shared by web pages with the same origin. However, the first-level domain names of the two web pages are the same, but the second-level domain names are different. The browser allows sharing cookies by setting document.domain.

For example, web page A is http://w1.example.com/a.html, web page B is http://w2.example.com/b .html, then as long as the same document.domain is set, the two web pages can share cookies.

document.domain = 'example.com';

Now, web page A sets a Cookie through a script

document.cookie = "test1=hello";

Web page B can read this Cookie.

var allCookie = document.cookie;

This method is only applicable to Cookie and iframe windows. LocalStorage and IndexDB cannot use this method.
To circumvent the same origin policy, you must use the PostMessage API introduced below.

In addition, the server can also specify the domain name of the cookie as the first-level domain name when setting the cookie, such as .example.com.

 Set-Cookie: key=value; domain=.example.com; path=/

In this case, both the second-level domain name and the third-level domain name can read this cookie without any settings.

2. iframe

If the two web pages have different sources, they cannot get the other party’s DOM. Typical examples are iframe windows and windows opened by the window.open method, which cannot communicate with the parent window.

For example, if the parent window runs the following command, if the iframe window is not from the same origin, an error will be reported

document.getElementById("myIFrame").contentWindow.document
 // Uncaught DOMException: Blocked a frame from accessing a cross-origin frame.

In the above command, the parent window wants to obtain the DOM of the child window, and an error will be reported because of cross-origin. .

Vice versa, the child window will also report an error when getting the DOM of the main window.

 window.parent.document.body    // 报错

If the first-level domain name of the two windows is the same, but the second-level domain name is different, then setting the document.domain attribute introduced in the previous section can circumvent the same-origin policy and get the DOM .

For websites with completely different origins, there are currently three methods to solve the communication problem of cross-domain windows.

  • fragment identifier
  • window.name
  • Cross-document messaging API

2.1 Fragment identifier

片段标识符(fragment identifier)指的是,URL的#号后面的部分,比如http://example.com/x.html#fragment的#fragment。如果只是改变片段标识符,页面不会重新刷新。

父窗口可以把信息写入子窗口的片段标识符。

var src = originURL + '#' + data;
document.getElementById('myIFrame').src = src;

子窗口通过监听hashchange事件得到通知。

window.onhashchange = checkMessage;

    function checkMessage() {
      var message = window.location.hash;
      // ...
    }

同样的,子窗口也可以改变父窗口的片段标识符。

 parent.location.href= target + "#" + hash;

2.2 window.name

浏览器窗口有window.name属性。这个属性的最大特点是,无论是否同源,只要在同一个窗口里,前一个网页设置了这个属性,后一个网页可以读取它。

父窗口先打开一个子窗口,载入一个不同源的网页,该网页将信息写入window.name属性。

window.name = data;

接着,子窗口跳回一个与主窗口同域的网址。

location = 'http://parent.url.com/xxx.html';

然后,主窗口就可以读取子窗口的window.name了。

var data = document.getElementById('myFrame').contentWindow.name;

这种方法的优点是,window.name容量很大,可以放置非常长的字符串;缺点是必须监听子窗口window.name属性的变化,影响网页性能。

2.3 window.postMessage

上面两种方法都属于破解,HTML5为了解决这个问题,引入了一个全新的API:跨文档通信 API(Cross-document messaging)。

这个API为window对象新增了一个window.postMessage方法,允许跨窗口通信,不论这两个窗口是否同源。

举例来说,父窗口http://aaa.com向子窗口http://bbb.com发消息,调用postMessage方法就可以了。

 var popup = window.open('http://bbb.com', 'title');
 popup.postMessage('Hello World!', 'http://bbb.com');

postMessage方法的第一个参数是具体的信息内容,第二个参数是接收消息的窗口的源(origin),即”协议 + 域名 + 端口”。也可以设为*,表示不限制域名,向所有窗口发送。

子窗口向父窗口发送消息的写法类似。

window.opener.postMessage('Nice to see you', 'http://aaa.com');

父窗口和子窗口都可以通过message事件,监听对方的消息。

window.addEventListener('message', function(e) {
  console.log(e.data);
},false);

message事件的事件对象event,提供以下三个属性。

    event.source:发送消息的窗口
    event.origin: 消息发向的网址
    event.data: 消息内容

下面的例子是,子窗口通过event.source属性引用父窗口,然后发送消息。

    window.addEventListener('message', receiveMessage);
    function receiveMessage(event) { 
       event.source.postMessage('Nice to see you!', '*');
    }

event.origin属性可以过滤不是发给本窗口的消息。

window.addEventListener('message', receiveMessage);
 function receiveMessage(event) {
   if (event.origin !== 'http://aaa.com') return;
   if (event.data === 'Hello World') {
       event.source.postMessage('Hello', event.origin);
   } else {
     console.log(event.data);
   }
 }

2.4 LocalStorage

通过window.postMessage,读写其他窗口的 LocalStorage 也成为了可能。

下面是一个例子,主窗口写入iframe子窗口的localStorage。

window.onmessage = function(e) {
   if (e.origin !== 'http://bbb.com') {
        return;
   }   
   var payload = JSON.parse(e.data);
   localStorage.setItem(payload.key, JSON.stringify(payload.data));
 };

上面代码中,子窗口将父窗口发来的消息,写入自己的LocalStorage。

父窗口发送消息的代码如下。

var win = document.getElementsByTagName('iframe')[0].contentWindow;
var obj = { name: 'Jack' };
win.postMessage(JSON.stringify({key: 'storage', data: obj}), 'http://bbb.com');

加强版的子窗口接收消息的代码如下。

window.onmessage = function(e) {
 if (e.origin !== 'http://bbb.com') return;
 var payload = JSON.parse(e.data);
 switch (payload.method) {
   case 'set':
     localStorage.setItem(payload.key, JSON.stringify(payload.data));
     break;
   case 'get':
     var parent = window.parent;
     var data = localStorage.getItem(payload.key);
     parent.postMessage(data, 'http://aaa.com');
     break;
   case 'remove':
     localStorage.removeItem(payload.key);
     break;
 }
};

加强版的父窗口发送消息代码如下。

var win = document.getElementsByTagName('iframe')[0].contentWindow;
 var obj = { name: 'Jack' };
 // 存入对象
 win.postMessage(JSON.stringify({key: 'storage', method: 'set', data: obj}), 'http://bbb.com');
 // 读取对象
 win.postMessage(JSON.stringify({key: 'storage', method: "get"}), "*");
 window.onmessage = function(e) {
   if (e.origin != 'http://aaa.com') return;
   // "Jack"
   console.log(JSON.parse(e.data).name);
 };

3、Ajax

同源政策规定,AJAX请求只能发给同源的网址,否则就报错。

除了架设服务器代理(浏览器请求同源服务器,再由后者请求外部服务),有三种方法规避这个限制。

    JSONP
    WebSocket
    CORS

3.1 JSONP

JSONP是服务器与客户端跨源通信的常用方法。最大特点就是简单适用,老式浏览器全部支持,服务器改造非常小。

它的基本思想是,网页通过添加一个<script></script>元素,向服务器请求JSON数据,这种做法不受同源政策限制;服务器收到请求后,将数据放在一个指定名字的回调函数里传回来。

首先,网页动态插入<script></script>元素,由它向跨源网址发出请求。

   function addScriptTag(src) {
      var script = document.createElement(&#39;script&#39;);
      script.setAttribute("type","text/javascript");
      script.src = src;
      document.body.appendChild(script);
    }

    window.onload = function () {
      addScriptTag(&#39;http://example.com/ip?callback=foo&#39;);
    }    function foo(data) {
      console.log(&#39;Your public IP address is: &#39; + data.ip);
    };

上面代码通过动态添加<script></script>元素,向服务器example.com发出请求。注意,该请求的查询字符串有一个callback参数,用来指定回调函数的名字,这对于JSONP是必需的。

服务器收到这个请求以后,会将数据放在回调函数的参数位置返回。

foo({
  "ip": "8.8.8.8"
});

由于<script></script>元素请求的脚本,直接作为代码运行。这时,只要浏览器定义了foo函数,该函数就会立即调用。作为参数的JSON数据被视为JavaScript对象,而不是字符串,因此避免了使用JSON.parse的步骤。

3.2 WebSocket

WebSocket是一种通信协议,使用ws://(非加密)和wss://(加密)作为协议前缀。该协议不实行同源政策,只要服务器支持,就可以通过它进行跨源通信。

下面是一个例子,浏览器发出的WebSocket请求的头信息(摘自维基百科)。

    GET /chat HTTP/1.1
    Host: server.example.com
    Upgrade: websocket
    Connection: Upgrade
    Sec-WebSocket-Key: x3JJHMbDL1EzLkh9GBhXDw==
    Sec-WebSocket-Protocol: chat, superchat
    Sec-WebSocket-Version: 13
    Origin: http://example.com

上面代码中,有一个字段是Origin,表示该请求的请求源(origin),即发自哪个域名。

正是因为有了Origin这个字段,所以WebSocket才没有实行同源政策。因为服务器可以根据这个字段,判断是否许可本次通信。如果该域名在白名单内,服务器就会做出如下回应。

HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: HSmrc0sMlYUkAGmm5OPpG2HaGWk=
Sec-WebSocket-Protocol: chat

3.3 CORS

CORS is the abbreviation of Cross-Origin Resource Sharing. It is a W3C standard and is the fundamental solution for cross-origin AJAX requests. Compared with JSONP which can only send GET requests, CORS allows any type of request.

[Related recommendations: javascript learning tutorial]

The above is the detailed content of What is the same origin policy in javascript. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Frontend Development with React: Advantages and TechniquesFrontend Development with React: Advantages and TechniquesApr 17, 2025 am 12:25 AM

The advantages of React are its flexibility and efficiency, which are reflected in: 1) Component-based design improves code reusability; 2) Virtual DOM technology optimizes performance, especially when handling large amounts of data updates; 3) The rich ecosystem provides a large number of third-party libraries and tools. By understanding how React works and uses examples, you can master its core concepts and best practices to build an efficient, maintainable user interface.

React vs. Other Frameworks: Comparing and Contrasting OptionsReact vs. Other Frameworks: Comparing and Contrasting OptionsApr 17, 2025 am 12:23 AM

React is a JavaScript library for building user interfaces, suitable for large and complex applications. 1. The core of React is componentization and virtual DOM, which improves UI rendering performance. 2. Compared with Vue, React is more flexible but has a steep learning curve, which is suitable for large projects. 3. Compared with Angular, React is lighter, dependent on the community ecology, and suitable for projects that require flexibility.

Demystifying React in HTML: How It All WorksDemystifying React in HTML: How It All WorksApr 17, 2025 am 12:21 AM

React operates in HTML via virtual DOM. 1) React uses JSX syntax to write HTML-like structures. 2) Virtual DOM management UI update, efficient rendering through Diffing algorithm. 3) Use ReactDOM.render() to render the component to the real DOM. 4) Optimization and best practices include using React.memo and component splitting to improve performance and maintainability.

React in Action: Examples of Real-World ApplicationsReact in Action: Examples of Real-World ApplicationsApr 17, 2025 am 12:20 AM

React is widely used in e-commerce, social media and data visualization. 1) E-commerce platforms use React to build shopping cart components, use useState to manage state, onClick to process events, and map function to render lists. 2) Social media applications interact with the API through useEffect to display dynamic content. 3) Data visualization uses react-chartjs-2 library to render charts, and component design is easy to embed applications.

Frontend Architecture with React: Best PracticesFrontend Architecture with React: Best PracticesApr 17, 2025 am 12:10 AM

Best practices for React front-end architecture include: 1. Component design and reuse: design a single responsibility, easy to understand and test components to achieve high reuse. 2. State management: Use useState, useReducer, ContextAPI or Redux/MobX to manage state to avoid excessive complexity. 3. Performance optimization: Optimize performance through React.memo, useCallback, useMemo and other methods to find the balance point. 4. Code organization and modularity: Organize code according to functional modules to improve manageability and maintainability. 5. Testing and Quality Assurance: Testing with Jest and ReactTestingLibrary to ensure the quality and reliability of the code

React Inside HTML: Integrating JavaScript for Dynamic Web PagesReact Inside HTML: Integrating JavaScript for Dynamic Web PagesApr 16, 2025 am 12:06 AM

To integrate React into HTML, follow these steps: 1. Introduce React and ReactDOM in HTML files. 2. Define a React component. 3. Render the component into HTML elements using ReactDOM. Through these steps, static HTML pages can be transformed into dynamic, interactive experiences.

The Benefits of React: Performance, Reusability, and MoreThe Benefits of React: Performance, Reusability, and MoreApr 15, 2025 am 12:05 AM

React’s popularity includes its performance optimization, component reuse and a rich ecosystem. 1. Performance optimization achieves efficient updates through virtual DOM and diffing mechanisms. 2. Component Reuse Reduces duplicate code by reusable components. 3. Rich ecosystem and one-way data flow enhance the development experience.

React: Creating Dynamic and Interactive User InterfacesReact: Creating Dynamic and Interactive User InterfacesApr 14, 2025 am 12:08 AM

React is the tool of choice for building dynamic and interactive user interfaces. 1) Componentization and JSX make UI splitting and reusing simple. 2) State management is implemented through the useState hook to trigger UI updates. 3) The event processing mechanism responds to user interaction and improves user experience.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)