How to change style of iframe content cross-domain?

by raphael_tillman , in category: Javascript , 10 months ago

How to change style of iframe content cross-domain?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by wilmer.lemke , 10 months ago

@raphael_tillman 

Changing the style of content inside an iframe that is hosted on a different domain is not possible due to security restrictions known as the "Same-origin policy". This policy prevents scripts from one origin (domain, protocol, and port) from accessing or modifying content of another origin.


The only way to change the style of the content inside an iframe from a different domain is if you have control over both the parent document and the iframe's content document, and both domains have proper CORS (Cross-Origin Resource Sharing) headers set. In that case, you can use postMessage to communicate between the two documents and modify the style of the iframe's content accordingly.


Here's an example of how you can achieve this:

  1. In the parent document, add an event listener for the "message" event:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
window.addEventListener("message", receiveMessage, false);

function receiveMessage(event) {
  // Check the origin of the message
  if (event.origin !== "https://example.com") {
    return;
  }

  // Modify the style of the iframe's content
  var iframe = document.getElementById("myIframe");
  iframe.contentWindow.postMessage("changeStyle", "https://example.com");
}


  1. In the content document of the iframe, add a listener for the "message" event:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
window.addEventListener("message", receiveMessage, false);

function receiveMessage(event) {
  // Check the origin of the message
  if (event.origin !== "https://parentdomain.com") {
    return;
  }

  // Change the style of the iframe's content
  var myElement = document.getElementById("myElement");
  myElement.style.color = "red";
}


  1. If the conditions are met and the cross-origin communication is allowed, the style of the content inside the iframe will be changed to red when the parent document sends the "changeStyle" message.


Please note that this method requires cooperation from both the parent and iframe's content documents, and appropriate CORS settings on the server hosting the iframe's content. If you do not have control over the content of the iframe or if CORS headers are not properly configured, you cannot change the style of the iframe's content.