How to get access to iframe element - javascript

I have the following html and javascript. If I click on simulate event I want the HandleEvents function to post the text into the 'child' page html. So I am essentially trying to latch onto an html element inside a child web page from a parent.
How do I do that?
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<script type="text/javascript">
function _bindEvent(el, eventName, eventHandler) {
if (el.addEventListener){
el.addEventListener(eventName, eventHandler, false);
} else if (el.attachEvent){
el.attachEvent('on'+eventName, eventHandler);
}
}
function doconfigure() {
var ifrm = document.getElementById('ifrm');
if(ifrm) {
ifrm.src="configure.html";
}
}
function doevents() {
var ifrm = document.getElementById('ifrm');
if(ifrm) {
ifrm.src="show_events.html";
}
}
function dooutbound() {
var ifrm = document.getElementById('ifrm');
if(ifrm) {
ifrm.src="outbound.html";
}
}
function HandleEvents(data) {
//post data to show_events.html page
var ifrm = document.getElementById('ifrm');
if(ifrm) {
ifrm.src="show_events.html";
}
//post to events field
var elem = top.frames['display'].document.getElementById('event');
if(elem) {
elem.innerHTML = data;
}
}
</script>
<title></title>
</head>
<body>
<fieldset>
<legend>Select</legend>
<input type="button" value="Configure" onclick="doconfigure();">
<input type="button" value="Events" onclick="doevents();">
<input type="button" value="Outbound" onclick="dooutbound();">
<input type="button" value="simulate event" onclick="HandleEvents('my event');">
<br />
</fieldset>
<iframe src="configure.html" name="display" id="ifrm" height="700" width="800">
<p>Your browser does not support iframes.</p>
</iframe>
</body>
</html>
Then the show_events.html page:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title></title>
</head>
<body>
<p>Events:</p>
<p id="event"></p>
</body>
</html>

You will not be able to do this unless the IFRAME shares the same origin as the parent script (for CSRF-protection purposes). If this requirement is met, it's all good.
jQuery is strongly recommended for this as things can get very, very messy very quickly.
You can gain access to the DOM of the IFRAME using the following:
jQuery (Fiddle: http://jsfiddle.net/ZYxVA/)
var myIFRAME = $("iframe#test");
var myContent = $("html",myIFRAME.contents());
Native (Fiddle: http://jsfiddle.net/L8Cek/)
var myIFRAME = document.getElementById("test");
var mC = myIFRAME.contentDocument,
mCbody = mC.getElementsByTagName("body")[0];
var docE = document.createElement("div");
docE.innerHTML = "this is a test";
mCbody.appendChild(docE);
As you can probably tell by now, jQuery is strongly recommended due to the fact that your code will get very hairy, very quickly otherwise. The quick run-down is, $("iframe").contents() allows you to get contentDocument. From there, you can run queries against that DOM by passing it as the second parameter.
In addition to this, you also will not be able to do anything until the iframe is fully loaded. You can listen to this by binding an onLoad event on it.

You need to wait for the iframe to be fully loaded before you can access the elements in the iframe.
Basic idea:
function HandleEvents (data) {
var myIframe = document.getElementById('ifrm');
myIframe.onload = function() {
var innerDoc = myIframe.contentDocument || myIframe.contentWindow.document;
var myElement = innerDoc.getElementById('event');
myElement.innerHTML = data;
};
myIframe.src = 'show_events.html';
}

Related

Redirect to differnent URL and load a javascript file

I am working on a project - When the URL to my site (www.mywebsite.com), is entered, I want it to go automatically go to a different website in the same browser window and then go another website (www.anotherWebsiteOne.com) in the same and the after X seconds will load another webSite (www.anotherWebSiteTwo.com) in the same browser, and so on.
I would like everytthing to stay in the same browser window
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>Basic Javascript Example</title>
<script type="text/javascript" src="webSites.js"></script>
</head>
<body onload="start()">
</body>
</html>
and my webSites.js:
var webSites = [
'http://www.anotherWebPageOne.com/',
'https://www.anotherWebPageTwo.com/',
'http:www.anotherWebPageThree.com/',
];
var iTarget;
function nextTarget(){
window.open( targets[iTarget], 'target' );
if( ++iTarget >= targets.length ) {
iTarget = 0;
}
}
function start() {
iTarget = 0;
nextTarget();
setInterval( nextTarget, 5000 );
}
start()
you can use :
<body onload="start()">
</body>
or you can simply add start() to the end of your js file
just add start() to end of your webSites.js file
whatever in your js file will be executed automatically and you have to just call the start function in the js file by invoking it.
also, rename your webSites variable to targets.
in your JS file you just need to add window.onload = <Your Function Name>;
eg:-
var webSites = [
'http://www.anotherWebPageOne.com/',
'https://www.anotherWebPageTwo.com/',
'http:www.anotherWebPageThree.com/',
];
var iTarget;
function nextTarget(){
window.open( targets[iTarget], 'target' );
if( ++iTarget >= targets.length ) {
iTarget = 0;
}
}
window.onload = nextTarget;
function start() {
iTarget = 0;
nextTarget();
setInterval( nextTarget, 5000 );
}
I hope it will solve your problem

Frameset innerHTML changes

I am trying to achieve something like, www.example.com/en/test/page.html will load the frameset of www.example.com/2.html.
Which I am able to do.
But now once 2.html is loaded in frameset I want to replace .html" to .html" target="_top".
So that all the links present in 2.html would be opened in the parent window instead of frameset itself.
<!DOCTYPE html">
<html lang='en' xml:lang='en' xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>Test Page</title>
<script>
(function divert()
{
var urlString = parent.document.URL;
var a1 = new RegExp("/en/test/page");
if(a1.test(urlString)) {document.write('<frameset cols="100%" rows="100%"><frame src="http://www.example.com/2.html"></frameset>');}
else{document.write('<frameset cols="100%" rows="100%"><frame src="http://www.example.com/3.html"></frameset>');}
var str = document.getElementById("demo").innerHTML;
var res = str.replace('.html"', '.html" target="_top"');
document.getElementById("demo").innerHTML = res;
})();
</script>
</head>
<body onLoad="divert()"></body>
Hi #Vinod you can use target="_parent"if you have only 2 level of frame-set or just want to open the link to the parent frame only..
Or to open the link to the current page you can use target="_top"
You can read more about it here
UPDATE:
You can also use JavaScript to detect if page is loaded inside a frame and than add target to the links pragmatically..
You can use window.location.origin and parent.window.location.origin to detect if you are in the frame
And than you can use following code to add target using JavaScript
using jquery:
$(document).ready(function(){
$('#link_other a').attr('target', '_blank');
});
without using jquery
window.onload = function(){
var anchors = document.getElementById('link_other').getElementsByTagName('a');
for (var i=0; i<anchors.length; i++){
anchors[i].setAttribute('target', '_blank');
}
}
<!DOCTYPE html">
<html lang='en' xml:lang='en' xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>Test Page</title>
<script>
(function divert()
{
var urlString = parent.document.URL;
var a1 = new RegExp("/en/test/page");
function targetUrl(){
var links = document.getElementById("demo").contentDocument.documentElement.getElementsByTagName('a');
for(var i =0; i<links.length; i++){
links[i].target = '_parent';}
}
if(a1.test(urlString)){document.write('<frameset cols="100%" rows="100%"><frame id="demo" src="http://www.example.com/2.html"></frameset>');}
else{document.write('<frameset cols="100%" rows="100%"><frame id="demo" src="http://www.example.com/3.html"></frameset>');}
document.getElementById("demo").onload= targetUrl;
})();
</script>
</head>
<body></body>
</html>

Appending HTML to parent from inside iFrame without jQuery

I'm developing in an application where new code is introduced via iframes only. I'm trying to create a function (running inside an iFrame) that will append some html after the iFrame in which it is running. I'd rather not introduce jQuery to resolve this issue. Here is a sample
function AppendDivAfteriFrame() {
var iFrame = window.parent.document.getElementById(window.frameElement.id)
var newDivInParent = window.parent.document.createElement('div');
newDivInParent.setAttribute("Id", "MyDiv");
newDivInParent.innerHTML = 'Hello World! I am outside the iFrame';
iFrame.appendChild(newDivInParent);
}
I don't receive any exceptions, but I never see any results either.
Update with full code
Call this page InnerPage.html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script type="text/javascript">
function AppendDivAfteriFrame() {
var iFrame = window.parent.document.getElementById(window.frameElement.id)
var newDivInParent = window.parent.document.createElement('div');
newDivInParent.setAttribute("Id", "MyDiv");
iFrame.appendChild(newDivInParent);
parent.document.getElementById('MyDiv').innerHTML = 'Hello World! I am outside the iFrame';
}
</script>
</head>
<body>
<button onclick="AppendDivAfteriFrame()">Append HTML</button>
</body>
</html>
Call this page OuterPage.html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
</head>
<body>
<iframe src="InnerPage.html" id="MyiFrame"></iframe>
</body>
</html>
This works:
function AppendDivAfteriFrame() {
var iFrame = window.parent.document.getElementById(window.frameElement.id)
var newDivInParent = window.parent.document.createElement('div');
newDivInParent.setAttribute("Id", "MyDiv");
iFrame.parentNode.appendChild(newDivInParent); //Edited here
parent.document.getElementById('MyDiv').innerHTML = 'Hello World! I am outside the iFrame';
}

Modal dialog (showModalDialog()) is not functioning properly in IE9

Scenario : There is an input element in a HTML page where u can enter any numbers/text. If 2 consecutive characters are entered, then I am calling showModalDialog() method to open a pop up window which is having another input element. Whatever the characters entered in parent page will be copied to that search box.
Issue : If user types a text fast(without break) for searching with more than 2 characters (for ex. apple) then 3rd and/or 4th character/s typed are missed out(not traced by keyUp event). I mean only aple word is copied into search box present in pop up. So user need to retype the text.
Solution needed : Whenever user types any text, pop up needs to be triggered and all the characters need to be copied into search box in pop up
Environment : Reproducing only in IE9
Languages : HTML, Javascript
Note : What I have analysed is, since there is a delay in triggering pop up window, characters typed after 2 charaters are missed out. I don't know why this is occuring only in IE9 also I can not upgrade to IE10 for resolving issue.
Still I am stucked up with this issue. Is there any alternative solution for this? Any other way to get all the functionality of modal dialog with some other element/s?
Here is the sample code snippet of parent HTML:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Test Page</title>
<script type="text/javascript">
var checkSeq = new RegExp("[a-zA-Z]{2}", "i");
function handleShowModalPopUp(fieldValue){
if(checkSeq.test(fieldValue)){
window.showModalDialog("popUpPage.html", document.getElementById('searchElem').value, "");
}
}
</script>
</head>
<body>
Enter Search Term :
<input type="text" id="searchElem" value="" onkeyup="handleShowModalPopUp(this.value)">
</body>
</html>
Here is the pop up window HTML (popUpPage.html) :
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Search Dialog</title>
<script type="text/javascript">
function handleOnload(){
var searchVal = window.dialogArguments;
if(null!= searchVal){
document.getElementById('searchElem').value = searchVal;
}
}
</script>
</head>
<body onload="handleOnload()">
<input type="text" id="searchElem">
<input type="button" value="Search">
</body>
</html>
What you actually want to do is delay the opening of the popup until your user has stopped typing. Detecting if a user has stopped typing is simply a matter of detecting if nothing has happened in the time a keystroke could have happened. So instead of opening the modal window, open it only after a delay on the condition that no keystroke happened in the meantime.
Here is some code I cooked up that should help you. I've set the delay 500ms.
<html>
<head>
<script>
function DelayedPopup(delayThreshold) {
this.delay = delayThreshold;
this.lastSearchValue = undefined;
this.popEvent = 0;
}
DelayedPopup.prototype = {
needsDelay: function() {
return this.searchValue() != this.lastSearchValue;
},
searchValue: function() {
return document.getElementById('searchElem').value;
},
openPopup: function() {
window.showModalDialog("popUpPage.html", "");
},
popupOrDelay: function() {
if (this.needsDelay()) {
this.popup();
}
else {
this.openPopup();
this.popEvent = 0;
}
},
popup: function() {
this.lastSearchValue = this.searchValue();
if (this.popEvent) {
clearInterval(this.popEvent);
}
var self = this;
this.popEvent = setTimeout(function() { self.popupOrDelay(); }, this.delay);
}
};
var delayedPopup = new DelayedPopup(500);
</script>
</head>
<body>
<input type="text" id="searchElem" onkeyup="if (this.value.length > 2) delayedPopup.popup()">
</body>
</html>

Scripts do not execute when changing the content of an iframe with innerHTML

I would like to load the content of an iframe with JavaScript. I don't want to change the src but directly the content with:
document.getElementById('frame').contentDocument.body.innerHTML = data;
It works but the JavaScript in data is not executed. Is it a security protection or I forgot something?
It looks like the problem is not the iframe, but the fact that scripts are not executed when inserted into the DOM text with innerHTML.
You may want to check the following Stack Overflow post for a couple of solutions:
Can scripts be inserted with innerHTML?
Use this for getting the document crossbrowser
//returns iframe document
function getIFrameDocument(iframe) {
var doc;
if (iframe.contentDocument) {//FF-Chrome
doc = iframe.contentDocument;
} else if (iframe.contentWindow) {
doc = iframe.contentWindow.document;
} else if (iframe.document) {//IE8
doc = iframe.document;
} else {
doc = window.frames[iframe.id].document;
}
return doc;
}
Try this
in a page index.html write:
<script type="text/javascript">
function init()
{
var s = document.createElement("script");
s.innerHTML="alert('ops');"
document.getElementById("frame").contentDocument.getElementsByTagName("body")[0].appendChild(s);
}
window.onload = init;
</script>
...
<body>
<form id="form1">
<div>
<iframe id="frame" src="test.html"></iframe>
</div>
</form>
</body>
Then simply write test.html like:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
</head>
<body>
</body>
</html>
and load from a web server index.html and the code works!!
Having something like the following would work.
<iframe id = "testframe" onload = populateIframe(this.id);></iframe>
// The following function should be inside a script tag
function populateIframe(id) {
var text = "This is a Test"
var iframe = getObj(id);
var doc;
if(iframe.contentDocument) {
doc = iframe.contentDocument;
} else {
doc = iframe.contentWindow.document;
}
doc.body.innerHTML = text;
}

Categories