How to append elements in head tag from iframe?

Member

by samara , in category: Javascript , 6 days ago

How to append elements in head tag from iframe?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by brandy , 5 days ago

@samara 

It is not possible to directly append elements in the head tag of the parent document from within an iframe due to the same-origin policy restrictions enforced by web browsers. This is a security measure to prevent cross-site scripting attacks.


However, you can communicate between the parent document and iframe using the window.postMessage() method. Here's how you can do it:

  1. In the parent document, add an event listener to listen for messages from the iframe:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
window.addEventListener('message', function(event) {
  if (event.origin !== 'http://example.com') { // Replace with the origin of your iframe
    return;
  }
  
  // Check the message sent from the iframe
  if (event.data.action === 'appendHeader') {
    // Append elements to the head tag
    var head = document.head;
    var element = document.createElement('link');
    element.setAttribute('rel', 'stylesheet');
    element.setAttribute('href', event.data.stylesheet);
    head.appendChild(element);
  }
});


  1. In the iframe, send a message to the parent document when you want to append elements to the head tag:
1
2
3
4
5
6
var message = {
  action: 'appendHeader',
  stylesheet: 'styles.css'  // Replace with the URL of your stylesheet
};

window.parent.postMessage(message, 'http://example.com'); // Replace with the origin of the parent document


By following these steps, you can effectively append elements to the head tag of the parent document from within an iframe.