Am I using on/postMessage correctly?

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

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().

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

I’m using a second parameter.

Correct answer is:

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

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.