Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>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:

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);
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading