Skip to content
Advertisement

Run code in a frame from one site to another with JavaScript

I have Site A and Site B. Site B is hosted on Site A in a frame. I can communicate between sites using this code:

Code on site A:

const frame = document.getElementById('frame');
frame.contentWindow.postMessage('Hello', 'https://www.test.com');

Code on site B:

window.addEventListener('message', event => {
   console.log(event.data);
});

This code is intended to forward the message. Can I pass code to execute from site A to site B, like change the background color on site B?

Advertisement

Answer

Can I pass code to execute from site A to site B

Only technically. You can only pass transferable objects which don’t include functions. That doesn’t stop you sending a string of JavaScript source code and then evaling it… but that comes with the usual caveats about eval (slow, hard to debug, increased security risk, etc).

Generally you should have the listener be prepared to do the actions you want and have the message include data that it understands should trigger that.

For example:

frame.contentWindow.postMessage({
    action: "changeBackground", 
    value: "#aabbcc"
}, 'https://www.test.com');

and

window.addEventListener('message', event => {
    if (event.data?.action === "changeBackground") 
        changeBackground(event.data?.value);
});
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement