Same origin Policy & Cross domain

The iframe cross-domain

Because of the same-origin policy, using the IFrame tag to import non-same-origin resources will block the DOM element of the iframe from being handled by the browser. Suppose you have two domains: blog.sch.com and game.sch.com. Load the game’s page in the blog page and manipulate its DOM elements.

<body>
    <div>This is outside window.</div>
    <iframe src="https://game.sch.com"></iframe>
    <script>
        const frame = document.querySelector('iframe')
        const frameDoc = frame.contentWindow.document
        // Manipulate DOM elements in non-homologous iframe
        frameDoc.body.innerHTML = 'This is iframe'
    </script>
</body>
Copy the code

The browser displays the following error:

Uncaught DOMException: Blocked a frame with origin “game.sch.com” from accessing a cross-origin frame.

Solution 1: Domain reduction

A descending domain is a cross-domain solution that makes document.domain of different domains homologous by designating them as their common parent domain. Blog.sch.com and game.sch.com share a common parent field, sch.com. Then change the domain of the pages under the two domain names to sch.com to solve the cross-domain problem.

document.domain = 'sch.com'
Copy the code

Matters needing attention:

  • document.domainThe specified field must be the current field or its parent.
  • When the subdomain and parent domain cross domains, the parent domain must also be specifieddocument.domain.

Disadvantages: Can only be used with the same parent field.

So what happens when the two main domains are completely different? This is where postMessage comes in.

Solution 2: postMessage

PostMessage is a new function in HTML5 that can be used to send messages to Windows.

window.postMessage(message, targetOrigin)
Copy the code

Message is the message (which can be an object) to be sent. The value of targetOrigin can be * or a URI that specifies the field in which the message can be received. * indicates that the message can be sent to any window. If the window’s field does not match the targetOrigin, the message will not be sent.

And if there is a send there will be a receive, otherwise it doesn’t mean anything. We can get the message sent by adding a Message event listener to the window.

window.addEventListener('message'.(event) = > {
    const { origin, source, data } = event
})
Copy the code

Origin is the sender’s domain and verifies that the sender of a message can be trusted. Source is the window object of the message sender, and you can use source.postMessage to send messages back to the sender. Data is the message content.