@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 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 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.