Skip to main content
Solved

Am I using on/postMessage correctly?

  • September 5, 2023
  • 4 replies
  • 1902 views

Hello,

I’m trying to send a message from code.js to ui.html but I’m getting the following error message: “Blocked a frame with origin ‘null’ from accessing a cross-origin frame.” Sending messages from the UI to code.js (which is my backend), works fine.

code.html

    figma.ui.onmessage = msg => {
        if (msg.type === 'importSvg') {
            const vectorNode = figma.currentPage.selection[0];
            console.log(vectorNode);
            figma.ui.postMessage({ type: 'vectorNode',vectorNode});
        }
    };

ui.html

parent.onmessage = msg => {
        if (msg.type === 'vectorNode') {
          console.log(msg.vectorNode);
        }
    };

Thank you

Best answer by Palettblad

Correct answer is:

onmessage = msg => {
        if (msg.type === 'vectorNode') {
          console.log(msg.vectorNode);
        }
    };
View original

4 replies

What is the code in code.js that is posting the message? You do need to pass a second parameter of "*" to specify any origin when calling postMessage().


  • Author
  • 3 replies
  • September 6, 2023

Sorry, I mixed up code js with ui.html. I’ve edited my post now.

I’m using a second parameter.


  • Author
  • 3 replies
  • Answer
  • September 6, 2023

Correct answer is:

onmessage = msg => {
        if (msg.type === 'vectorNode') {
          console.log(msg.vectorNode);
        }
    };

  • 2 replies
  • September 11, 2023

This error “Blocked a frame with origin from accessing a cross-origin frame” is not a bug. The same-origin policy is a security mechanism that ensures that window objects only have access to the informations they are authorized to get. To fix this issue, ensure that both the parent page and the iframe content are served from the same domain or implement Cross-Origin Communication techniques such as postMessage to safely communicate and exchange data between the two frames.

The window.postMessage() method provides a controlled mechanism to securely circumvent this Same-Origin Policy restriction. The window.postMessage() safely enables cross-origin communication between Window objects; e.g: between a page and an iframe embedded within it.

postMessage(message, targetOrigin)
postMessage(message, targetOrigin, [transfer])

targetOrigin - specifies what the origin of targetWindow must be for the event to be dispatched, either as the literal string “*” (indicating no preference) or as a URI.

If you don’t have control over the content in the iframe, you won’t be able to directly access its elements due to security restrictions.


Reply


Cookie policy

We use cookies to enhance and personalize your experience. If you accept you agree to our full cookie policy. Learn more about our cookies.

 
Cookie settings