Can you explain the distinction between postMessage() and dispatchEvent() in relation to the origin policy?

Here is some code that I wrote. I tried setting the MessageEvent's origin to *, but I'm still getting an error in the console saying "Blocked a frame with origin "AAAA" from accessing a frame with origin "BBBB". Protocols, domains, and ports must match.". Any ideas on why this might be happening?


var size = {
  width: document.body.scrollWidth,
  height: document.body.scrollHeight
}

var evt = new MessageEvent("dimensionMessage",{
    "data": size,
    "origin":"*"
});

window.parent.dispatchEvent(evt);

Interestingly, when I use

window.parent.postMessage(size, "*")
, it seems to work without any issues.

Answer №1

The message displayed indicates that a cross-origin iframe is unable to call a method from the parent page unless they share the same origin. This restriction includes methods like dispatchEvent, as allowing this could potentially lead to security vulnerabilities such as fake mouse events being triggered in the parent page.

However, an exception to this rule is the postMessage API, which is specifically designed to enable secure communication between different origins.

Incorporating origin's value as '*' will not solve the issue in this context. Normally, the browser automatically assigns this property when using postMessage. Manually creating a MessageEvent object is typically only necessary if you want to mimic the receipt of an external message on the receiving end.

Answer №2

When two different documents are not from the same origin, their access is restricted due to Same-origin policy limitations.

For instance, dispatchEvent() has limited capabilities when interacting with a separate frame like window.parent.

window.postMessage() enables cross-window messaging without being hindered by Same-origin policy constraints.

The targetOrigin parameter for window.postMessage() specifies the required origin of the otherWindow in order for the event to be delivered, either as "*" (indicating no specific preference) or as a URI.

It's important to note that in production code, it is advisable to use a precise URI to enhance the security of your implementation. More guidance on securely utilizing window.postMessage() can be found at https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the proper method for utilizing the "oneOf" keyword in this schema?

Is it possible to have either option A or B, but not both (mutually exclusive)? In Draft 3, I am required to use whatever is available, even though the version on top says 4. This is because when using an array for "required", it throws an error stating t ...

The element type 'x' in JSX does not offer any construct or call signatures

I have recently imported an image and I am trying to use it within a function. The imported image is as follows: import Edit from 'src/assets/setting/advertising/edit.png'; This is the function in question: function getOptions(row) { ...

Using JavaScript to calculate dimensions based on the viewport's width and height

I have been trying to establish a responsive point in my mobile Webview by implementing the following JavaScript code: var w = window.innerWidth-40; var h = window.innerHeight-100; So far, this solution has been working effectively. However, I noticed th ...

Ways to transfer data from JavaScript to Wicket framework

My Javascript method executes business logic on the client side and returns a value. I now want to access this value in my Wicket page. What is the most effective approach for achieving this? P.S. I am currently using Wicket 7. ...

Updating the div#content dynamically with Jquery without the need to refresh the page

After spending countless hours on this forum, I have yet to find a solution that perfectly fits my needs, so I will pose my question. Here is the gist of what I am attempting to accomplish: When the page loads, the default page fades in and displays. Wh ...

Merge information from various sources using ajax

Currently, I have a single ajax request that retrieves data from an API and uses it to generate a table. Now, I'm looking to modify the code so that it can retrieve data from two different URLs and merge them into the same table (retTable). Below is ...

Stop procrastinating and take action before the JavaScript function concludes

Currently, I am experimenting with onkeydown events to capture the input value in a textarea, process it through a PHP file using Ajax post method, and display the result in an external div. However, the issue is that whenever a key is pressed, I am unable ...

Utilize a button in React as a way to simultaneously submit a form and redirect with an href

I've created a form where users can input their information and click on a send button to submit it (see code below, button at the end). The form works fine, but when a user clicks on send, the input disappears which might give the impression that the ...

The JavaScript "sort()" method outlined in the Mozilla Documentation specifically created for the sorting of numbers

When it comes to sorting numbers in JavaScript, we can utilize the sort() function with a specific trick that yields perfect results. The tip for successful number sorting is as follows: [12, 2, 23, 3, 43, 54].sort(function (a, b) { return a - b ; } ) S ...

Filtering elements using two dropdown lists

In my list, each li element has data-name and data-body attributes. I want to display only the li elements that match the selected values. The first select option is for selecting the car name, while the second select option is for selecting the car body. ...

Exploring the Node environment setup within Nest.js

Currently, I am in the midst of setting up a Nest.js project and seeking an efficient solution for defining the Node environment used by the ConfigService to load environment variables: import { Module } from '@nestjs/common'; import { ConfigSer ...

Jade not binding correctly with Angular.ErrorMessage: Angular bindings are

Struggling with simple binding in Angular and Jade. I've tried moving JavaScript references to the end of the document based on advice from previous answers, but still no luck. Any ideas on what might be wrong? File: angular.jade extends layout blo ...

WordPress is failing to reference the standard jQuery file

I am currently attempting to include the jQuery DataTable JS file in my plugin to showcase database query results using DataTable. The JS file is stored locally on the server. Information about versions: WordPress: v4.0.1 jQuery: v1.11.1 DataTable: v1.10 ...

Toggle the visibility of the identical div

I am facing a challenge with dynamically hiding and showing various div elements on my website. I have managed to achieve this using show/hide, but the issue arises when I need to show/hide some of the same fields repeatedly. The script works fine on the f ...

Updating state in Redux from a different componentorModifying state

I'm currently learning about redux and I'm facing an issue with accessing the stored state (id) in my components. Specifically, I have a Footer component with a button that is supposed to modify the state in the Layout component. However, I am un ...

Can the serialization of AJAX URL parameters in jQuery be customized?

Is there a way to instruct jQuery or an AJAX call on how to format query string parameters other than writing a custom serializer? I am using a jQuery AJAX call and passing an object with URL parameters var params = {name: 'somename', favColors ...

Colorful radial spinner bar

I am interested in replicating the effect seen in this video: My goal is to create a spinner with text in the center that changes color, and when the color bar reaches 100%, trigger a specific event. I believe using a plugin would make this task simpler, ...

The absence of jasmine-node assertions in promises goes unnoticed

Everything seems to be running smoothly with the code below, except for the assertion part. Whenever I run the test using Jasmine, it reports 0 assertions. Is there a way to include my assertions within promises so they are recognized? it("should open sav ...

"What is the best way to access and extract data from a nested json file on an

I've been struggling with this issue for weeks, scouring the Internet for a solution without success. How can I extract and display the year name and course name from my .json file? Do I need to link career.id and year.id to display career year cours ...

The hierarchy of precedence when using the TypeScript Type Assertion operator

Is it necessary to wrap the js-ternary operator with 'as' Type Assertion? ios ? TouchableOpacity : View as React.ElementType Will it automatically use the result of '?:' since it comes first? Or would a better implementation be: (ios ...