Reputation: 11
I want to be able to execute code inside someones else's page.
Here is an example for easy understanding:
Lets say I want to change the color of some iframe page after it is loaded:
document.body.style.backgroundColor = "#AAAAAA";
document.getElementById('targetFrame').contentWindow.targetFunction();
Upvotes: 1
Views: 1118
Reputation: 34038
If it's someone else's page. You just plain cannot do this without some cooperation from the other party. Think about the implications this would have for security on the Web if random people such as yourself could arbitrarily run code against applications written by other developers? While I'm sure you're of good character, there is enough people out there of low moral fiber to where this would be a huge issue for data security.
With that said, there are exceptions to this security rule; however.
For instance, if the other Web developer gives you permission to execute code on his or her page, you could use the HTML5 window.postMessage API to pass a message from one context to another and then run a command when that message is received.
To clarify, this requires that the other developer register a listener in his/her website to listen to events that are sent from your website.
Code on your Colleague's site:
// register to listen for postMessage events
window.addEventListener("message", changeBackground, false);
// this is the callback handler to process the event
function changeBackground(event)
{
// you're colleage is responsible for making sure only YOU can
// make calls to his/her site!
if (event.origin !== "http://example.org:8080")
return;
// event.data could contain "#AAAAAA" for instance
document.body.style.backgroundColor = event.data;
// do other stuff
}
}
Your code:
// pass the string "#AAAAAA" to the iframe page, where the changeBackground
// function will change the color
document.getElementById("theIframe").contentWindow.postMessage("#AAAAAA", targetOrigin);
In order to execute this code when the iframe is finished loading, you would of course need to be able to detect this, which could be accomplished either using the iframe's load event or by having your colleague use postMessage in reverse, to notify you to fire your event..
For more information, check out the HTML5 Specification on Web Messaging.
Upvotes: 3