Javascript --> iframe resizing using postMessage method - javascript

I'm trying to understand another Stackoverflow answer (cross-domain iframe resizer?) that purports to solve how to resize an iframe (hosted on a domain separate from the domain it's embedded in) according to its height. Wondering if anyone could answer my questions below.
THE SOLUTION:
Iframe:
<!DOCTYPE html>
<head>
</head>
<body onload="parent.postMessage(document.body.scrollHeight, 'http://target.domain.com');">
<h3>Got post?</h3>
<p>Lots of stuff here which will be inside the iframe.</p>
</body>
</html>
The parent page which contains the iframe (and would like to know its height):
<script type="text/javascript">
function resizeCrossDomainIframe(id, other_domain) {
var iframe = document.getElementById(id);
window.addEventListener('message', function(event) {
if (event.origin !== other_domain) return; // only accept messages from the specified domain
if (isNaN(event.data)) return; // only accept something which can be parsed as a number
var height = parseInt(event.data) + 32; // add some extra height to avoid scrollbar
iframe.height = height + "px";
}, false);
}
</script>
<iframe src='http://example.com/page_containing_iframe.html' id="my_iframe" onload="resizeCrossDomainIframe('my_iframe', 'http://example.com');">
</iframe>
MY QUESTIONS:
http://target.domain.com refers to the domain the iframe is
embedded within, right? NOT the domain that the iframe is hosted on?
In the function resizeCrossDomainIframe(id, other_domain) { line, I'm not supposed to interchange "id" with the id of the iframe and "other_domain" with the domain name that the iframe is hosted on, right? They're only parameters that I specify later when I call the function.
Instead of using onload within the iframe tag, I wrote the equivalent in jQuery, which loads on the page that embeds the iframe:
$('#petition-embed').load(function() {
resizeCrossDomainIframe('petition-embed','http://target.domain.com');
});
I added brackets around return:
if (event.origin !== other_domain) {return;} // only accept messages from the specified domain
if (isNaN(event.data)) {return;} // only accept something which can be parsed as a number
Does that look right?

I needed to do something similar, and found this example that seems simpler: using postmessage to refresh iframe's parent document
Here is what I ended up with in the iframe:
window.onload = function() {
window.parent.postMessage(document.body.scrollHeight, 'http://targetdomain.com');
}
And in the receiving parent:
window.addEventListener('message', receiveMessage, false);
function receiveMessage(evt){
if (evt.origin === 'http://sendingdomain.com') {
console.log("got message: "+evt.data);
//Set the height on your iframe here
}
}

Related

SVG contentDocument null when SVG loads dynamic in Ionic3 [duplicate]

For say i have a Site called example.com on which iframe is embedded of domain iframe.net, now i want to read the content of iframe and pass some parameter to display a textual message. Like Hi with username.
Now the problem is this able not able to make connection between the two , even am not able to get the innerHTML of iframe i used following approach
document.getElementById('myframe').contentWindow.document.body.innerHTML;
It throws error "Permission denied to access property"
Do anyone know how to read and write in cross domain platform
If you don't have control over the framed site, you cannot circumvent the cross-domain policy.
If you have control over both sites, you can use the postMessage method to transfer data across different domains. A very basic example:
// framed.htm:
window.onmessage = function(event) {
event.source.postMessage(document.body.innerHTML, event.origin);
};
// Main page:
window.onmessage = function(event) {
alert(event.data);
};
// Trigger:
// <iframe id="myframe" src="framed.htm"></iframe>
document.getElementById('myframe').contentWindow.postMessage('','*');
In Internet Explorer 8, events passed as a parameter may be null, that is why you need to access the event in a different manner:
In frame.html:
window.onmessage = function(event) {
var evt = event || window.event;
evt.source.postMessage('Message from iFrame', evt.origin);
};
On main.html:
window.onmessage = function(event) {
var evt = event || window.event;
alert(evt.data);
};
The event is triggered the same way as Rob W has presented:
document.getElementById('frameId').contentWindow.postMessage('message','*');
It can happen only if you have control for both sites
you can use postMessage
here's how you can apply it
first, you can add the below code to the site you want to retrieve data from
<script>
function test() {
document.getElementById('idMyIframe').contentWindow.postMessage("your message here", "*");
}
</script>
<iframe id="idMyIframe" onload="test()" src="http://example.otherdomaintosenddatato.com"></iframe>
the second step you can add this code below to the other domain you want to send a message or the data to it
window.addEventListener("message", function (message) {
if (message.origin == "http://firstdomain.com") {
console.log(message)
}
});
and please note you must add the test() function on the onload attribute of the iframe cause if the function runs before the iframe was loaded it will become useless and it won't send data
Cross Domain iframe elements access in React with (srcDoc):-
<iframe srcDoc={this.state.HTML} width='100%' id='iframetnd' onLoad={this.onclickinsideiframe}/>
onclickinsideiframe=()=>{
if(document.getElementById('iframetnd')!==null){
let iframe = document.getElementById('iframetnd');
let innerDocument = (iframe.contentDocument)
? iframe.contentDocument
: iframe.contentWindow.document;
let Obj = innerDocument.getElementsByClassName("navButtons")[0];
if(Obj !== undefined){
Obj.onclick = ()=>this.func();
}
}
}
func=()=>{
this.setState({page:2})
this.arrangeTest();
}
iFrame does not allow to access contents from Cross Domain platform. You can only access if your iFrame is using the same domain.
This solution works same as iFrame. I have created a PHP script that can get all the contents from the other website, and most important part is you can easily apply your custom jQuery to that external content. Please refer to the following script that can get all the contents from the other website and then you can apply your cusom jQuery/JS as well. This content can be used anywhere, inside any element or any page.
<div id='myframe'>
<?php
/*
Use below function to display final HTML inside this div
*/
//Display Frame
echo displayFrame();
?>
</div>
<?php
/*
Function to display frame from another domain
*/
function displayFrame()
{
$webUrl = 'http://[external-web-domain.com]/';
//Get HTML from the URL
$content = file_get_contents($webUrl);
//Add custom JS to returned HTML content
$customJS = "
<script>
/* Here I am writing a sample jQuery to hide the navigation menu
You can write your own jQuery for this content
*/
//Hide Navigation bar
jQuery(\".navbar.navbar-default\").hide();
</script>";
//Append Custom JS with HTML
$html = $content . $customJS;
//Return customized HTML
return $html;
}

Accessing DOM elements inside nested HTML and BODY tags [duplicate]

For say i have a Site called example.com on which iframe is embedded of domain iframe.net, now i want to read the content of iframe and pass some parameter to display a textual message. Like Hi with username.
Now the problem is this able not able to make connection between the two , even am not able to get the innerHTML of iframe i used following approach
document.getElementById('myframe').contentWindow.document.body.innerHTML;
It throws error "Permission denied to access property"
Do anyone know how to read and write in cross domain platform
If you don't have control over the framed site, you cannot circumvent the cross-domain policy.
If you have control over both sites, you can use the postMessage method to transfer data across different domains. A very basic example:
// framed.htm:
window.onmessage = function(event) {
event.source.postMessage(document.body.innerHTML, event.origin);
};
// Main page:
window.onmessage = function(event) {
alert(event.data);
};
// Trigger:
// <iframe id="myframe" src="framed.htm"></iframe>
document.getElementById('myframe').contentWindow.postMessage('','*');
In Internet Explorer 8, events passed as a parameter may be null, that is why you need to access the event in a different manner:
In frame.html:
window.onmessage = function(event) {
var evt = event || window.event;
evt.source.postMessage('Message from iFrame', evt.origin);
};
On main.html:
window.onmessage = function(event) {
var evt = event || window.event;
alert(evt.data);
};
The event is triggered the same way as Rob W has presented:
document.getElementById('frameId').contentWindow.postMessage('message','*');
It can happen only if you have control for both sites
you can use postMessage
here's how you can apply it
first, you can add the below code to the site you want to retrieve data from
<script>
function test() {
document.getElementById('idMyIframe').contentWindow.postMessage("your message here", "*");
}
</script>
<iframe id="idMyIframe" onload="test()" src="http://example.otherdomaintosenddatato.com"></iframe>
the second step you can add this code below to the other domain you want to send a message or the data to it
window.addEventListener("message", function (message) {
if (message.origin == "http://firstdomain.com") {
console.log(message)
}
});
and please note you must add the test() function on the onload attribute of the iframe cause if the function runs before the iframe was loaded it will become useless and it won't send data
Cross Domain iframe elements access in React with (srcDoc):-
<iframe srcDoc={this.state.HTML} width='100%' id='iframetnd' onLoad={this.onclickinsideiframe}/>
onclickinsideiframe=()=>{
if(document.getElementById('iframetnd')!==null){
let iframe = document.getElementById('iframetnd');
let innerDocument = (iframe.contentDocument)
? iframe.contentDocument
: iframe.contentWindow.document;
let Obj = innerDocument.getElementsByClassName("navButtons")[0];
if(Obj !== undefined){
Obj.onclick = ()=>this.func();
}
}
}
func=()=>{
this.setState({page:2})
this.arrangeTest();
}
iFrame does not allow to access contents from Cross Domain platform. You can only access if your iFrame is using the same domain.
This solution works same as iFrame. I have created a PHP script that can get all the contents from the other website, and most important part is you can easily apply your custom jQuery to that external content. Please refer to the following script that can get all the contents from the other website and then you can apply your cusom jQuery/JS as well. This content can be used anywhere, inside any element or any page.
<div id='myframe'>
<?php
/*
Use below function to display final HTML inside this div
*/
//Display Frame
echo displayFrame();
?>
</div>
<?php
/*
Function to display frame from another domain
*/
function displayFrame()
{
$webUrl = 'http://[external-web-domain.com]/';
//Get HTML from the URL
$content = file_get_contents($webUrl);
//Add custom JS to returned HTML content
$customJS = "
<script>
/* Here I am writing a sample jQuery to hide the navigation menu
You can write your own jQuery for this content
*/
//Hide Navigation bar
jQuery(\".navbar.navbar-default\").hide();
</script>";
//Append Custom JS with HTML
$html = $content . $customJS;
//Return customized HTML
return $html;
}

cross domain iframe resize for firefox 3.6.10

Is there any way to resize a cross domain iframe according to its content, that would work in Firefox 3.6.10?
I thought that the postMessage command works, but a solution I found works in Firefox 12 but not in Firefox 3.6.10. Or maybe that's not the problem.
As I wrote in another question, youtube seems to be just embedding the content of the iframe in the page for the comment section, that's how it gets resized dynamically. And this would basically solve every iframe issue too, since the HTML would be embedded in the website's local HTML, and no same origin policy would block anything. When I asked about this, I didn't get answers though.
So thank you in advance, or if you don't like when people say that, I would be grateful if someone would helped.
And I CAN control the content inside the frame too!
(I need this for a script that makes youtube look like around 2012, so more people could be grateful too.)
You might try looking at this on GitHub.
https://github.com/davidjbradshaw/iframe-resizer
solution i found/modified:
in the page which contains the iframe:
<script type="text/javascript">
function resizeCrossDomainIframe(id, other_domain) {
var iframe = document.getElementById(id);
window.addEventListener('message', function(event) {
if (event.origin !== other_domain) return;
if (isNaN(event.data)) return;
var height = parseInt(event.data) + 32;
iframe.height = height + "px";
}, false);
}
in the iframe code:
<iframe id="my_iframe" onload="resizeCrossDomainIframe('my_iframe', '**whatever domain your iframe content is on**');"></iframe>
for continuous resizing, i put this in the page containing the iframe:
<script>
var interval = setInterval(function(){
resizeCrossDomainIframe('my_iframe', '**whatever domain your iframe content is on**');
}, 100);
</script>
on the iframe content page:
<script>
window.onload = function() {
window.parent.postMessage(document.body.scrollHeight, '**whatever domain your iframe containing page is on**');
}
</script>
and this for continuous resizing:
<script>
var interval2 = setInterval(function(){
window.parent.postMessage(document.body.scrollHeight, '**whatever domain your iframe containing page is on**');
}, 100);
</script>
CORRECTION: the first interval script isnt needed, since the eventlistener executes the function every time a message is sent to it. it would just cause slowness

Resize Parent Frame to fit iFrame Height [duplicate]

I tried a few solutions but wasn't successful. I'm wondering if there is a solution out there preferably with an easy-to-follow tutorial.
You have three alternatives:
1. Use iFrame-resizer
This is a simple library for keeping iFrames sized to their content. It uses the PostMessage and MutationObserver APIs, with fall backs for IE8-10. It also has options for the content page to request the containing iFrame is a certain size and can also close the iFrame when your done with it.
https://github.com/davidjbradshaw/iframe-resizer
2. Use Easy XDM (PostMessage + Flash combo)
Easy XDM uses a collection of tricks for enabling cross-domain communication between different windows in a number of browsers, and there are examples for using it for iframe resizing:
http://easyxdm.net/wp/2010/03/17/resize-iframe-based-on-content/
http://kinsey.no/blog/index.php/2010/02/19/resizing-iframes-using-easyxdm/
Easy XDM works by using PostMessage on modern browsers and a Flash based solution as fallback for older browsers.
See also this thread on Stackoverflow (there are also others, this is a commonly asked question). Also, Facebook would seem to use a similar approach.
3. Communicate via a server
Another option would be to send the iframe height to your server and then poll from that server from the parent web page with JSONP (or use a long poll if possible).
I got the solution for setting the height of the iframe dynamically based on it's content. This works for the cross domain content.
There are some steps to follow to achieve this.
Suppose you have added iframe in "abc.com/page" web page
<div>
<iframe id="IframeId" src="http://xyz.pqr/contactpage" style="width:100%;" onload="setIframeHeight(this)"></iframe>
</div>
Next you have to bind windows "message" event under web page "abc.com/page"
window.addEventListener('message', function (event) {
//Here We have to check content of the message event for safety purpose
//event data contains message sent from page added in iframe as shown in step 3
if (event.data.hasOwnProperty("FrameHeight")) {
//Set height of the Iframe
$("#IframeId").css("height", event.data.FrameHeight);
}
});
On iframe load you have to send message to iframe window content with "FrameHeight" message:
function setIframeHeight(ifrm) {
var height = ifrm.contentWindow.postMessage("FrameHeight", "*");
}
On main page that added under iframe here "xyz.pqr/contactpage" you have to bind windows "message" event where all messages are going to receive from parent window of "abc.com/page"
window.addEventListener('message', function (event) {
// Need to check for safety as we are going to process only our messages
// So Check whether event with data(which contains any object) contains our message here its "FrameHeight"
if (event.data == "FrameHeight") {
//event.source contains parent page window object
//which we are going to use to send message back to main page here "abc.com/page"
//parentSourceWindow = event.source;
//Calculate the maximum height of the page
var body = document.body, html = document.documentElement;
var height = Math.max(body.scrollHeight, body.offsetHeight,
html.clientHeight, html.scrollHeight, html.offsetHeight);
// Send height back to parent page "abc.com/page"
event.source.postMessage({ "FrameHeight": height }, "*");
}
});
What I did was compare the iframe scrollWidth until it changed size while i incrementally set the IFrame Height. And it worked fine for me. You can adjust the increment to whatever is desired.
<script type="text/javascript">
function AdjustIFrame(id) {
var frame = document.getElementById(id);
var maxW = frame.scrollWidth;
var minW = maxW;
var FrameH = 100; //IFrame starting height
frame.style.height = FrameH + "px"
while (minW == maxW) {
FrameH = FrameH + 100; //Increment
frame.style.height = FrameH + "px";
minW = frame.scrollWidth;
}
}
</script>
<iframe id="RefFrame" onload="AdjustIFrame('RefFrame');" class="RefFrame"
src="http://www.YourUrl.com"></iframe>
I have a script that drops in the iframe with it's content. It also makes sure that iFrameResizer exists (it injects it as a script) and then does the resizing.
I'll drop in a simplified example below.
// /js/embed-iframe-content.js
(function(){
// Note the id, we need to set this correctly on the script tag responsible for
// requesting this file.
var me = document.getElementById('my-iframe-content-loader-script-tag');
function loadIFrame() {
var ifrm = document.createElement('iframe');
ifrm.id = 'my-iframe-identifier';
ifrm.setAttribute('src', 'http://www.google.com');
ifrm.style.width = '100%';
ifrm.style.border = 0;
// we initially hide the iframe to avoid seeing the iframe resizing
ifrm.style.opacity = 0;
ifrm.onload = function () {
// this will resize our iframe
iFrameResize({ log: true }, '#my-iframe-identifier');
// make our iframe visible
ifrm.style.opacity = 1;
};
me.insertAdjacentElement('afterend', ifrm);
}
if (!window.iFrameResize) {
// We first need to ensure we inject the js required to resize our iframe.
var resizerScriptTag = document.createElement('script');
resizerScriptTag.type = 'text/javascript';
// IMPORTANT: insert the script tag before attaching the onload and setting the src.
me.insertAdjacentElement('afterend', ifrm);
// IMPORTANT: attach the onload before setting the src.
resizerScriptTag.onload = loadIFrame;
// This a CDN resource to get the iFrameResizer code.
// NOTE: You must have the below "coupled" script hosted by the content that
// is loaded within the iframe:
// https://unpkg.com/iframe-resizer#3.5.14/js/iframeResizer.contentWindow.min.js
resizerScriptTag.src = 'https://unpkg.com/iframe-resizer#3.5.14/js/iframeResizer.min.js';
} else {
// Cool, the iFrameResizer exists so we can just load our iframe.
loadIFrame();
}
}())
Then the iframe content can be injected anywhere within another page/site by using the script like so:
<script
id="my-iframe-content-loader-script-tag"
type="text/javascript"
src="/js/embed-iframe-content.js"
></script>
The iframe content will be injected below wherever you place the script tag.
Hope this is helpful to someone. 👍
I ran into this issue while working on something at work (using React). Basically, we have some external html content that we save into our document table in the database and then insert onto the page under certain circumstances when you're in the Documents dataset.
So, given n inlines, of which up to n could contain external html, we needed to devise a system to automatically resize the iframe of each inline once the content fully loaded in each. After spinning my wheels for a bit, this is how I ended up doing it:
Set a message event listener in the index of our React app which checks for a a specific key that we will set from the sender iframe.
In the component that actually renders the iframes, after inserting the external html into it, I append a <script> tag that will wait for the iframe's window.onload to fire. Once that fires, we use postMessage to send a message to the parent window with information about the iframe id, computed height, etc.
If the origin matches and the key is satisfied in the index listener, grab the DOM id of the iframe that we pass in the MessageEvent object
Once we have the iframe, just set the height from the value that is passed from the iframe postMessage.
// index
if (window.postMessage) {
window.addEventListener("message", (messageEvent) => {
if (
messageEvent.data.origin &&
messageEvent.data.origin === "company-name-iframe"
) {
const iframe = document.getElementById(messageEvent.data.id)
// this is the only way to ensure that the height of the iframe container matches its body height
iframe.style.height = `${messageEvent.data.height}px`
// by default, the iframe will not expand to fill the width of its parent
iframe.style.width = "100%"
// the iframe should take precedence over all pointer events of its immediate parent
// (you can still click around the iframe to segue, for example, but all content of the iframe
// will act like it has been directly inserted into the DOM)
iframe.style.pointerEvents = "all"
// by default, iframes have an ugly web-1.0 border
iframe.style.border = "none"
}
})
}
// in component that renders n iframes
<iframe
id={`${props.id}-iframe`}
src={(() => {
const html = [`data:text/html,${encodeURIComponent(props.thirdLineData)}`]
if (window.parent.postMessage) {
html.push(
`
<script>
window.onload = function(event) {
window.parent.postMessage(
{
height: document.body.scrollHeight,
id: "${props.id}-iframe",
origin: "company-name-iframe",
},
"${window.location.origin}"
);
};
</script>
`
)
}
return html.join("\n")
})()}
onLoad={(event) => {
// if the browser does not enforce a cross-origin policy,
// then just access the height directly instead
try {
const { target } = event
const contentDocument = (
target.contentDocument ||
// Earlier versions of IE or IE8+ where !DOCTYPE is not specified
target.contentWindow.document
)
if (contentDocument) {
target.style.height = `${contentDocument.body.scrollHeight}px`
}
} catch (error) {
const expectedError = (
`Blocked a frame with origin "${window.location.origin}" ` +
`from accessing a cross-origin frame.`
)
if (error.message !== expectedError) {
/* eslint-disable no-console */
console.err(
`An error (${error.message}) ocurred while trying to check to see ` +
"if the inner iframe is accessible or not depending " +
"on the browser cross-origin policy"
)
}
}
}}
/>
Here is an alternative implementation.
Basically if you able to edit page at other domain you can place another iframe page that belongs to your server which saving height to cookies.
With an interval read cookies when it is updated, update the height of the iframe. That is all.
Edit: 2019 December
The solution above basically uses another iframe inside of an iframe 3rd iframe is belongs to the top page domain, which you call this page with a query string that saves size value to a cookie, outer page checks this query with some interval. But it is not a good solution so you should follow this one:
In Top page :
window.addEventListener("message", (m)=>{iframeResizingFunction(m)});
Here you can check m.origin to see where is it comes from.
In frame page:
window.parent.postMessage({ width: 640, height:480 }, "*")
Although, please don't forget this is not so secure way. To make it secure update * value (targetOrigin) with your desired value.
Please follow documentation: https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage
I found another server side solution for web dev using PHP to get the size of an iframe.
First is using server script PHP to an external call via internal function: (like a file_get_contents with but curl and dom).
function curl_get_file_contents($url,$proxyActivation=false) {
global $proxy;
$c = curl_init();
curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($c, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.2; en-US; rv:1.8.1.7) Gecko/20070914 Firefox/2.0.0.7");
curl_setopt($c, CURLOPT_REFERER, $url);
curl_setopt($c, CURLOPT_URL, $url);
curl_setopt($c, CURLOPT_FOLLOWLOCATION, 1);
if($proxyActivation) {
curl_setopt($c, CURLOPT_PROXY, $proxy);
}
$contents = curl_exec($c);
curl_close($c);
$dom = new DOMDocument();
$dom->preserveWhiteSpace = false;
#$dom->loadHTML($contents);
$form = $dom->getElementsByTagName("body")->item(0);
if ($contents) //si on a du contenu
return $dom->saveHTML();
else
return FALSE;
}
$url = "http://www.google.com"; //Exernal url test to iframe
<html>
<head>
<script type="text/javascript">
</script>
<style type="text/css">
#iframe_reserve {
width: 560px;
height: 228px
}
</style>
</head>
<body>
<div id="iframe_reserve"><?php echo curl_get_file_contents($url); ?></div>
<iframe id="myiframe" src="http://www.google.com" scrolling="no" marginwidth="0" marginheight="0" frameborder="0" style="overflow:none; width:100%; display:none"></iframe>
<script type="text/javascript">
window.onload = function(){
document.getElementById("iframe_reserve").style.display = "block";
var divHeight = document.getElementById("iframe_reserve").clientHeight;
document.getElementById("iframe_reserve").style.display = "none";
document.getElementById("myiframe").style.display = "block";
document.getElementById("myiframe").style.height = divHeight;
alert(divHeight);
};
</script>
</body>
</html>
You need to display under the div (iframe_reserve) the html generated by the function call by using a simple echo curl_get_file_contents("location url iframe","activation proxy")
After doing this a body event function onload with javascript take height of the page iframe just with a simple control of the content div (iframe_reserve)
So I used divHeight = document.getElementById("iframe_reserve").clientHeight; to get height of the page external we are going to call after masked the div container (iframe_reserve). After this we load the iframe with its good height that's all.

Get IFrame's document, from JavaScript in main document

I have this HTML code:
<html>
<head>
<script type="text/javascript">
function GetDoc(x)
{
return x.document ||
x.contentDocument ||
x.contentWindow.document;
}
function DoStuff()
{
var fr = document.all["myframe"];
while(fr.ariaBusy) { }
var doc = GetDoc(fr);
if (doc == document)
alert("Bad");
else
alert("Good");
}
</script>
</head>
<body>
<iframe id="myframe" src="http://example.com" width="100%" height="100%" onload="DoStuff()"></iframe>
</body>
</html>
The problem is that I get message "Bad". That mean that the document of iframe is not got correctly, and what is actualy returned by GetDoc function is the parent document.
I would be thankful, if you told where I do my mistake. (I want to get document hosted in IFrame.)
Thank you.
You should be able to access the document in the IFRAME using the following code:
document.getElementById('myframe').contentWindow.document
However, you will not be able to do this if the page in the frame is loaded from a different domain (such as google.com). This is because of the browser's Same Origin Policy.
The problem is that in IE (which is what I presume you're testing in), the <iframe> element has a document property that refers to the document containing the iframe, and this is getting used before the contentDocument or contentWindow.document properties. What you need is:
function GetDoc(x) {
return x.contentDocument || x.contentWindow.document;
}
Also, document.all is not available in all browsers and is non-standard. Use document.getElementById() instead.
In case you get a cross-domain error:
If you have control over the content of the iframe - that is, if it is merely loaded in a cross-origin setup such as on Amazon Mechanical Turk - you can circumvent this problem with the <body onload='my_func(my_arg)'> attribute for the inner html.
For example, for the inner html, use the this html parameter (yes - this is defined and it refers to the parent window of the inner body element):
<body onload='changeForm(this)'>
In the inner html :
function changeForm(window) {
console.log('inner window loaded: do whatever you want with the inner html');
window.document.getElementById('mturk_form').style.display = 'none';
</script>
You can also use:
document.querySelector('iframe').contentDocument

Categories

Resources