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', '');

Code on site B:

window.addEventListener('message', event => {

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?

>Solution :

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:

    action: "changeBackground", 
    value: "#aabbcc"
}, '');


window.addEventListener('message', event => {
    if ( === "changeBackground") 

Leave a Reply Cancel reply