Skip to content Skip to sidebar Skip to footer

Manipulate Iframe From A Different Domain

For context, I am designing an Ionic mobile app for my website. However, I don't believe that this question is limited to the Ionic framework. Within my app, I want to display a fu

Solution 1:

I don't believe this is possible between sites of different origins. The chief problem with the proposed approach is not CORS but cross-site scripting. However, it is possible to use postMessage() to send a message from the parent window to the iframe, executing a javascript code hidden in the iframe source. This javascript can then manipulate the elements within the page.

This is the solution that I ultimately got to work:

Parent window

var frame = document.getElementById('myFrame').contentWindow;

sendMessage = function(e) {
    frame.postMessage('secret command', 'https://endpoint.com');
}

<iframe data-tap-disabled="true" id="myFrame" src="https://endpoint.com/index.php" onload="sendMessage()"></iframe>

Child (page loaded in the iframe) contains this script:

<script>window.onload = function() {
    // A function to process messages received by the window.functionreceiveMessage(e) {
        if (e.data == "secret command")
            //put code here to maniuplate page elements however desiredelsereturn;
    }

    // Setup an event listenerwindow.addEventListener('message', receiveMessage);
}
</script>

The end product is that the page loaded in the iframe can be displayed in a certain way depending on the command passed from the parent window. For my use, the page loaded in the iframe hides the navigation bars only when loaded from within my app.

Solution 2:

This definitely possible however you will bump into CORS issues so that is something that you need to keep in mind. You must keep in mind that none of the scripts or includes will be added so for the best experience host this on a page that loads all of your scripts and includes before you run this. You can see a super basic example here however you will get a CORS error so to see it working you will need to install the chrome CORS plugin and activate it.

You will see that the call is very simple

$('#test').load('https://stackoverflow.com/questions/50955345/manipulate-iframe-from-a-different-domain #question'); 

use the # tag to indicate the id of the content to load. So if you want to load the div with the id of 'MySuperCoolAndInterestingDiv' you just add ' #MySuperCoolAndInterestingDiv' to the end of you URL, the space between the URL and the hashtag are important, don't forget it.

Post a Comment for "Manipulate Iframe From A Different Domain"