I need to pass data from a web page to an iFrame hosted in that web page. I used window.postMessage. however the iFrame does not receive the event.
Here is my code snippet.
Parent page:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>Test event listener</title>
</head>
<body>
<script type="text/javascript">
function SendMsgToIFrame() {
alert("In Parent window ");
var myiframe = document.getElementById('myIframe');
if (myiframe.contentDocument) {
myiframe.contentDocument.postMessage('Post Message from Parent', '*');
}
else if (myiframe.contentWindow) {
myiframe.contentWindow.postMessage('Post Message from Parent', '*');
}
</script>
<button type="button" onclick="SendMsgToIFrame()">Push to iframe</button>
<div id="iframeDiv">
<iframe id="myIframe" src="http://localhost:50000/Receiver.htm" width="500" height="200" frameborder=10>
</iframe>
</div>
</body>
</html>
Code snippet for Receiver.htm is:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>Got Text</title>
</head>
<body>
<script type="text/javascript">
window.attachEvent("onMessage", myhandler);
function myhandler(mobj) {
alert("I am in iFrame");
var message = mobj.data;
alert("data: " + message);
}
</script>
<input type="text" name="text1" id="text1" value="text here" />
</body>
</html>
I am running the parent page on Tomcat (localhost:8080). The iFrame is running on my HTTP server I built using the httplistener.
When I run the parent page and hit the button that generates the event, I do not get the alert "I am in iFrame". Looks like the iFrame is not receiving the event at all. What am I missing here?
Any help is very much appreciated. Thanks!
Your code has some strange parts. You're using attachEvent where it's better to use addEventListener and you should probably post to contentWindow, not document.
The problem with my code was this:
window.attachEvent("onMessage", myhandler)
onmessage should be all lower case.
Once I changed this line to the below, it worked.
window.attachEvent("onmessage", myhandler)
I posted the answer here: javascript cross domain iframe resize
And that link also has a link to sample working code on github.
Related
I have a very simple setup on a dev server (both pages are on my local test server localhost:5500) where I have a main page
<!DOCTYPE html>
<html lang="en">
<head>
<title>Example Mockup</title>
</head>
<body>
<iframe src="./nested.html" id="frame"></iframe>
<script>
var iframe = document.getElementById('frame');
console.log(iframe.contentDocument.body);
</script>
</body>
</html>
and a nested page
<html>
<body>
<div id="hello">Hello, World</div>
</body>
</html>
when I load the main page in my browser the output written to console is: <body></body>
I can access the element #hello using iframe.contentDocument.getElementById('hello') but I want the body element including child elements. Can anyone please explain to me why is this happening
You have to wait until iframe loaded completely to access it's body.
var iframe = document.getElementById('frame');
iframe.onload = function () {
console.log(iframe.contentDocument.body);
}
I have a html file which contains iframe like below lines of code. Note that this iframe is displayed by one of tiny mce jquery and is rendered in browser as
below
<html>
<body>
<textarea id="texteditor"></textarea>
<div class="mceeditor">
<iframe>
<html>
<body>
<script type="text/javascript">
function mySubmit() {
var URL = "http://localhost:61222/14CommunityImages/hands.png";
window.document.getElementById("texteditor").value = URL;
}
</script>
</body>
</html>
</iframe>
</div>
</body>
</html>
Now my goal is to append var url inside text area which is in parent html tag.
Please help me !!!
The document in the iframe can access its parent window via parent, and its parent window's document via parent.document. So:
parent.document.getElementById("texteditor").value = URL;
Note: To access each-other's documents, the main document and the iframe must be on the same origin. If they're on different origins, they can still communicate, but only if they both do so expressly, via web messaging.
Side note: Your iframe, as shown in the question, won't work. Inline content in iframes is for display when the browser doesn't support iframes. You use a separate resource (e.g., page) identified by the src attribute (or you use the srcdoc attribute; I have no idea how well supported it is), for the iframe's content.
E.g.:
Main page:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Main Page</title>
<body>
<textarea id="texteditor"></textarea>
<div class="mceeditor">
<iframe src="theframe.html"></iframe>
</div>
</body>
</html>
theframe.html:
<!doctype html>
<html>
<body>
<input type="button" value="Click to set" onclick="mySubmit()">
<script type="text/javascript">
function mySubmit() {
var URL = "http://localhost:61222/14CommunityImages/hands.png";
parent.document.getElementById("texteditor").value = URL;
}
</script>
</body>
</html>
I'm trying to get the content of iframe in a javascript alert but, the alert appears empty
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>Untitled</title>
</head>
<style>
iframe {height:200px; width:300px; border:1px solid #000}
</style>
<script>
var iframe = document.getElementById("myFrame");
var iframe_contents = iframe.contentDocument.body.innerHTML;
function newDoc() {
alert (document.getElementById('myFrame').innerHTML) ;
}
</script>
<body>
<iframe src="http://api.adf.ly/api.php?key=c02fe2b360ee4b566a4f1e14d84b279b&uid=3141484&advert_type=banner&domain=adf.ly&url=http://somewebsite.com" id="myFrame">
</iframe><br>
</br>
<img src="http://www.giftworksconnect.com/wp-content/uploads/2012/10/download.png" width="100" onclick="newDoc(); return false;" style=" cursor: pointer;" border="0" id="adflink" />
</body>
</html>
any help would be appreciated
Regards
Edit:
I'm trying to get the contents of an IFRAME because I'm using Adf.ly
Api
"http://api.adf.ly/api.php?key=c02fe2b360ee4b566a4f1e14d84b279b&uid=3141484&advert_type=banner&domain=adf.ly&url=http://somewebsite.com"
But this api respond with a blank page with the shortend url I want to
use the shortened url directly in my site script
I guess your main (parent) page is on another domain. In this case your access to the iframe content is forbidden due to cross-domain restrictions.
If you don't have control over the inner page (api.adf.ly/api.php) you can't handle it on with the client-side code on your page.
replace Your below line
alert (document.getElementById('myFrame').innerHTML) ;
with the below
alert(document.getElementById('myFrame').src);
Think it will work for You.
My concept is to update the value of the text box in the main page from the iframe . This code is working in firefox , but not working in Internet Explorer and Chrome . Both main.html and frame.html are in same location . I need suggestions to make it work in all the browsers .
main.html
<!DOCTYPE html>
<html>
<head>
<title> main window </title>
</head>
<body>
Parent textbox :<input type="text" id="parentbox"></br></br></br>
<iframe src="frame.html" ></iframe>
</body>
</html>
frame.html
<!DOCTYPE html>
<html>
<head>
<title> frame window </title>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
function PushValues()
{
var frame_value = document.getElementById("framebox").value;
window.parent.document.getElementById("parentbox").value =frame_value;
}
</script>
</head>
<body>
<input type="text" id="framebox" >
<input type="button" value ="fill" onclick="PushValues()">
</body>
</html>
As per security policies, cross-domain access is restricted. This will happen if you are trying to show a page from domain 1 in domain 2 and try to manipulate the DOM of page in domain 2 from the script in domain 1. If you are running the pages from same location on a server. This shouldn't happen. However, if you are just saving them as HTML files and trying to open them in your browser, it should not work. I have created two jsbins for your code and it is working on chrome. Try to access them using the below links.
Main.html: http://jsbin.com/afazEDE/1
iframe.html: http://jsbin.com/ayacEXa/1/
Try to run main.html in edit mode in JSBin by keeping console open in chrome (F12) and click fill button. It will not work and will show you the error. If you run them as it is (in run mode of JSBin), it will work.
Jquery -
function PushValues()
{
var frame_value = $('#framebox').val();
parent.$('body').find('#parentbox').val(frame_value);
}
It's always work for me.
Run this code on a server like xamp or wamp it wont work directly
Main.html
<!DOCTYPE html>
<html>
<head>
<title> main window </title>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
</head>
<body>
Parent textbox :<input type="text" id="parentbox" value=""></br></br></br>
<iframe src="iframe.html"></iframe>
<script>
window._fn = {
printval: function (response) {
$("input").val(response);
},
};
</script>
</body>
iframe
<!DOCTYPE html>
<html>
<head>
<title> frame window </title>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
</head>
<body>
<input type="text" id="framebox">
<input type="button" value="fill" onclick="PushValues()">
<script language="javascript">
function PushValues() {
window.parent._fn['printval']($('input').val());
}
</script>
</body>
</html>
Since you're using jQuery try this
var frame_value = $('#framebox').val();
$('#parentbox', window.parent.document).val(frame_value);
You should try P3P policy which is highly related to iframes and Internet Explorer.
response header set to the iframe document
header key= 'P3P' header value: 'CP="IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT"'
I think this is a very simple question, but I can't seem to get it to work. I need to use JavaScript (specifically jQuery, apparently) to grab some content from a page, and pull it into another page. I've researched this quite a bit, but can't seem to get even a very simple example to work.
Here is the page I'm trying to get content from:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Test</title>
</head>
<body>
<p>This is the test html page.</p>
</body>
</html>
Here is the page I'm trying to use to pull the content:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>PullData</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js">
</head>
<body>
<ol id="result"></ol>
<script type="text/javascript">
$('#result').load('test.html');
</script>
</body>
</html>
When I open the page it doesn't seem to do anything. I'm basically trying to follow the examples from jquery.com: http://api.jquery.com/load/
Both html pages are in the same folder somewhere on my C drive.
What am I missing?
Thanks in advance for your help!
What browser are you using?
Because of same-origin policy, some browsers won't permit AJAX requests to file:/// URLs, even if the original file was loaded that way. I know this is true of Chrome, but haven't tested others.
What does your .load() error handler say? Oh...
It seems to make logical sense.
Checking the API on load you may want to see if it actually loads, or if it encoutners an error
$("#result").load("/not-here.php", function(response, status, xhr) {
if (status == "error") {
var msg = "Sorry but there was an error: ";
$("#result").html(msg + xhr.status + " " + xhr.statusText);
}
});
API LINK: http://api.jquery.com/load/
sometimes the debugging information is a good first step to any solution.
You have your script tags at the end of your page, which means the enclosed JS will be invoked as soon as the browser reaches it, which may not be before the DOM is ready (which means the <ol> might not be set up to get the content of test.html). Try enclosing your load in a $(document).ready() callback as follows:
<script type="text/javascript">
$(document).ready(function() {
$('#result').load('test.html');
});
</script>
Also why are you inserting a full HTML page into an ordered list? You should try an HTML snippet (no head & body tags) into a content holder such as <div> or <span> where it will be semantically correct.
If none of these things work, attach a callback as follows:
$('#result').load('test.html', null, function(responseText, textStatus, xhr) {
alert(textStatus); // see what the response status is
});
Where is the closing script tag?
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js">
</head>
Your code needs to be
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
</head>
You must first check if your HTML is ready.
$(document).ready(function() {
$('#result').load('test.html');
});
To ensure #result1 is loaded, you need a document.ready event handler:
<script type="text/javascript">
$(document).ready(function(){
$('#result').load('test.html');
});
</script>
Hope this helps. Cheers