Invoking a function in an iframe from the parent window - javascript

I can't figure out what I'm doing wrong here.
I am building a website with no server-side
I have a main page with an iframe and on a button click I want the iframe's src to change and a function in it to be invoked with a passed parameter.
The function is not called for some reason.
here's my code:
the iframe:
<iframe id="main_area_frame" name="main_area_frame" src="" frameborder="0" width="100%" height="100%"></iframe>
the onclick function:
function onSubMenuClick(images)
{
//Set Images Frame
main_area = document.getElementById("main_area_frame");
main_area.src = "ImagesFrame.html";
main_area.contentWindow.initializeImages(images);
}
the function in the iframe(ImagesFrame.html):
function initializeImages(imagesStr)
{
alert("initializeImages");
...
}
some weird things I noticed are that
when adding an alert just before main_area.contentWindow.initializeImages(images);
the function is somehow called successfully.
if I set the iframe's src from the begining and skip the line main_area.src = "ImagesFrame.html"; - the function is again, called.
any ideas?

Not sure if that is the cause, but I would try putting a delay(sleep) between
main_area.src = "ImagesFrame.html";
and
main_area.contentWindow.initializeImages(images);
in order to allow the iframe to be rendered (I do not know if it is the rendered by the same frame or the browser launches a new one).
Just my two cents.

I have had success with publishing the function from the child iframe during
onload handling. For example, (substituting your funcName):
In child iframe, edit body tag (or use equivalent javascript)
<body onload='top.funcName = funcName'>
In parent page, edit javascript; now the
funcName will be generally accessible as,
value = top.funcName( )

Related

HTML object is blocking eventlistener

I have imported a svg as an object in HTML:
<object data="mySVG.svg" type="image/svg+xml" id="circle">
<img src="mySVG.svg" />
</object>
and I am trying to set an eventlistener on the whole page:
window.addEventListener('click', function(){
alert('Hello')
})
The problem is that the object blocks the eventlistener and when the user clicks on the image the alert is not fired. But when the user clicks anywhere else or over other elements, the alert is fired. How can I make it so the object is acting as the other elements and doesn't block the eventlistener?
I tried wait after the object is beaing loaded and then set the eventlistener but it didn't work.
If I import the SVG directly into HTML with svg tag it works, but the svg is quit big and it makes the HTML code really messy. I can't use the img tag either becuase I am also interacting with parts of the SVG with JS later.
As it can be seen in this codepen I've made: https://codepen.io/Dimertuper/pen/rNJoLrK (When you click outside the image it triggers, inside the image it doesn't)
Your <object> acts like an <iframe>, just like we wouldn't want any website to be able to embed our bank website in an iframe and see where we clicked, the <object> has the same "protection".
Even if the page are same-origin and can talk to each other, by default they won't receive any events from the other one.
But anyway what you probably want is to make the SVG document react to these events. For this, add the event listeners on that document directly.
// Wait for the <object> to be loaded
window.addEventListener("load", (evt) => {
const objEl = document.querySelector("object");
const svgDoc = objEl.getSVGDocument();
// Now you have access to the SVG document
// you can add event listeners to it as you wish
svgDoc.addEventListener("click", (evt) => {
console.log("clicked on", evt.target.outerHTML);
});
});
Unfortunately StackSnippets's null-origined iframes won't allow us to make live demos, so here is one on JSFiddle.
But beware the <object> element isn't gathering much love from implementers and spec authors these days and it may get removed from the standards at some point in the future.
So instead, you may prefer to actually use an <iframe> directly. Moreover since here we would access the loaded document, we can do the one thing that <object> can do and <iframe> can't: auto-resizing to the image content.
For this, when we get our SVG document, we grab its documentElement's BBox and set our <iframe>'s width and height attributes to the BBox's ones.
// Wait for the <iframe> to be loaded
window.addEventListener("load", (evt) => {
const frameEl = document.querySelector("iframe");
const svgDoc = frameEl.getSVGDocument();
// Resize the iframe to its content's size
const bbox = svgDoc.documentElement.getBBox();
frameEl.width = bbox.width;
frameEl.height = bbox.height;
svgDoc.addEventListener("click", (evt) => {
console.log("clicked on", evt.target.outerHTML);
});
});
Once again as a JSFiddle.
Per OP's requirements -
Needs to be able to click on window/document and receive the alert message even when clicking on the HTML object tag.
We can do this by removing the object tag as a clickable element with CSS pointer-events: none;.
object {
pointer-events: none;
}
https://codepen.io/LTFoReal/pen/NWyerZg?editors=1111
This link has work around. Using a transparent div to cover object image, or directly use svg image instead.
I checked the specification of object element. It's for embeded external content usage. So it has ability to load a full document, your case is load as image. The available property to do event binding for this element is contentDocument or getSvgDocument(). Both are null under your case, as it's loaded as svg image.
document.getElementsByTagName("object")[0].contentDocument
Check this link for detail. Hope this helps you.

JavaScript tasks

I have been learning JavaScript and I have been doing some tasks, which I got in my college.
Tasks go like this:
Make a webpage, where 3 200x150 images and one 600x450 image will appear. Add JavaScript function, which will make sure, that the 600x450 image shown will be an enlarged image of an 200x150 image, on which we have pointed with a mouse previously (call the function with onMouseOver).
The second task goes like this:
Complete the webpage from task 1 in a way, when clicking the smaller image, the bigger image of the same image, we clicked will appear in a new window.
The code for the 1st task looks like this:
function bigImg(x)
{
x.style.height="600px";
x.style.width="450px";
}
function normalImg(x)
{
x.style.height="200px";
x.style.width="150px";
}
...
<img onmouseover="bigImg(this)" onmouseout="normalImg(this)" border="0" src="slika1.jpg" alt="slika1" width="150" height="200">
<img src="slika2.jpg">
<img src="slika3.jpg">
For the 2nd one like this:
function swipe()
{
var largeImage = document.getElementById('Slika1');
largeImage.style.display = 'block';
largeImage.style.width=450+"px";
// enter code here
var url=largeImage.getAttribute('src');
window.open(url,'Image','width=largeImage.style.width,height=largeImage.style.height,resizable=1');
}
...
<img src="slika1.jpg" id= "Slika1" onClick="swipe();"/>
<img src="slika2.jpg">
<img src="slika3.jpg">
What should be done differently?
<script>
function swipe(image)
{
newWidth=450+"px";
newHeight=600+"px";
var url=image.getAttribute('src');
myWindow=window.open('','Image','width='+newWidth+',height='+newHeight+',resizable=1');
myWindow.document.write('<img src="'+url+'" width="'+newWidth+'" height="'+newHeight+'" />');
}
</script>
<img src="slika1.jpg" onClick="swipe(this);"/>
<img src="slika2.jpg" onClick="swipe(this);"/>
<img src="slika3.jpg" onClick="swipe(this);"/>
To answer a few questions of the original poster:
The first parameter in the window.open() function here is '' (empty string), which basically creates a blank web page. The return value of this function call is the newly opened web page (which is assigned to the variable myWindow). You then drill down into that window object and call it's document.write() function to actually display the desired HTML (the image). In your original code you were simply opening a window that browsed to the image file (not an HTML page). Since that was the case, there is no way you could have actually set the width or height of the image--you were just setting (or trying to) the width and height of the window. Setting the width and height of the window wasn't even working in your example code because you didn't break the variable out of the string. So in the window.open() function you needed to pass a string in the third parameter that looked like:
width=450px,height=600px,resize=1
But what you were actually passing was:
width=largeImage.style.width,height=largeImage.style.height,resizable=1
The swipe() function we created takes in a single parameter "image". When we call this function from the onClick event inside the img tag we use the keyword "this" to pass a reference of itself. Essentially a copy of the img object that called swipe() is passed in as a parameter. So in the function, image.getAttribute('src') references the "src" attribute of the img object that called it, which you need to display in the opened window.

How to move an iFrame in the DOM without losing its state?

Take a look at this simple HTML:
<div id="wrap1">
<iframe id="iframe1"></iframe>
</div>
<div id="warp2">
<iframe id="iframe2"></iframe>
</div>
Let's say I wanted to move the wraps so that the #wrap2 would be before the #wrap1. The iframes are polluted by JavaScript. I am aware of jQuery's .insertAfter() and .insertBefore(). However, when I use those, the iFrame loses all of its HTML, and JavaScript variables and events.
Lets say the following was the iFrame's HTML:
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
// The variable below would change on click
// This represents changes on variables after the code is loaded
// These changes should remain after the iFrame is moved
variableThatChanges = false;
$(function(){
$("body").click(function(){
variableThatChanges = true;
});
});
</script>
</head>
<body>
<div id='anything'>Illustrative Example</div>
</body>
</html>
In the above code, the variable variableThatChanges would...change if the user clicked on the body. This variable, and the click event, should remain after the iFrame is moved (along with any other variables/events that have been started)
My question is the following: with JavaScript (with or without jQuery), how can I move the wrap nodes in the DOM (and their iframe childs) so that the iFrame's window stays the same, and the iFrame's events/variables/etc stay the same?
It isn't possible to move an iframe from one place in the dom to another without it reloading.
Here is an example to show that even using native JavaScript the iFrames still reload:
http://jsfiddle.net/pZ23B/
var wrap1 = document.getElementById('wrap1');
var wrap2 = document.getElementById('wrap2');
setTimeout(function(){
document.getElementsByTagName('body')[0].appendChild(wrap1);
},10000);
This answer is related to the bounty by #djechlin
A lot of search on the w3/dom specs and didn't find anything final that specifically says that iframe should be reloaded while moving in the DOM tree, however I did find lots of references and comments in the webkit's trac/bugzilla/microsoft regarding different behavior changes over the years.
I hope someone will find anything specific regarding this issue, but for now here are my findings:
According to Ryosuke Niwa - "That's the expected behavior".
There was a "magic iframe" (webkit, 2010), but it was removed in 2012.
According to MS - "iframe resources are freed when removed from the DOM". When you appendChild(node) of existing node - that node is first removed from the dom.
Interesting thing here - IE<=8 didn't reload the iframe - this behavior is (somewhat) new (since IE>=9).
According to Hallvord R. M. Steen comment, this is a quote from the iframe specs
When an iframe element is inserted into a document that has a browsing context, the user agent must create a new browsing context, set the element's nested browsing context to the newly-created browsing context, and then process the iframe attributes for the "first time".
This is the most close thing I found in the specs, however it's still require some interpretation (since when we move the iframe element in the DOM we don't really do a full remove, even if the browsers uses the node.removeChild method).
Whenever an iframe is appended and has a src attribute applied it fires a load action similarly to when creating an Image tag via JS. So when you remove and then append them they are completely new entities and they refresh. Its kind of how window.location = window.location will reload a page.
The only way I know to reposition iframes is via CSS. Here is an example I put together showing one way to handle this with flex-box:
https://jsfiddle.net/3g73sz3k/15/
The basic idea is to create a flex-box wrapper and then define an specific order for the iframes using the order attribute on each iframe wrapper.
<style>
.container{
display: flex;
flex-direction: column;
}
</style>
<div class="container">
<div id="wrap1" style="order: 0" class="iframe-wrapper">
<iframe id="iframe1" src="https://google.com"></iframe>
</div>
<div id="warp2" style="order: 1" class="iframe-wrapper">
<iframe id="iframe2" src="https://bing.com"></iframe>
</div>
</div>
As you can see in the JS fiddle these order styles are inline to simplify the flip button so rotate the iframes.
I sourced the solution from this StackOverflow question: Swap DIV position with CSS only
Hope that helps.
If you have created the iFrame on the page and simply need to move it's position later try this approach:
Append the iFrame to the body and use a high z-index and top,left,width,height to put the iFrame where you want.
Even CSS zoom works on the body without reloading which is awesome!
I maintain two states for my "widget" and it is either injected in place in the DOM or to the body using this method.
This is useful when other content or libraries will squish or squash your iFrame.
BOOM!
Unfortunately, the parentNode property of an HTML DOM element is read-only. You can adjust the positions of the iframes, of course, but you can't change their location in the DOM and preserve their states.
See this jsfiddle I created that provides a good test bed. http://jsfiddle.net/RpHTj/1/
Click on the box to toggle the value. Click on the "move" to run the javascript.
This question is pretty old... but I did find a way to move an iframe without it reloading. CSS only. I have multiple iframes with camera streams, I dont like when they reload when i swap them. So i used a combination of float, position:absolute, and some dummy blocks to move them around without reloading them and having the desired layout on demand (resizing and all).
If you are using the iframe to access pages you control, you could create some javascript to allow your parent to communicate with the iframe via postMessage
From there, you could build login inside the iframe to record state changes, and before moving dom, request that as a json object.
Once moved, the iframe will reload, you can pass the state data into the iframe and the iframe listening can parse the data back into the previous state.
PaulSCoder has the right solution. Never manipulate the DOM for this purpose. The classic approach for this is to have a relative position and "flip" the positions in the click event. It's only not wise to put the click event on the body, because it bubbles from other elements too.
$("body").click(function () {
var frame1Height = $(frame1).outerHeight(true);
var frame2Height = $(frame2).outerHeight(true);
var pos = $(frame1).css("top");
if (pos === "0px") {
$(frame1).css("top", frame2Height);
$(frame2).css("top", -frame1Height);
} else {
$(frame1).css("top", 0);
$(frame2).css("top", 0);
}
});
If you only have content that is not cross-domain you could save and restore the HTML:
var htmlContent = $(frame).contents().find("html").children();
// do something
$(frame).contents().find("html").html(htmlContent);
The advantage of the first method is, that the frame keeps on doing what it was doing. With the second method, the frame gets reloaded and starts it's code again.
At least in some circumstances a shadow dom with slotting might be an option.
<template>
<style>div {outline:1px solid black; height:45px}</style>
<div><slot name="a" /></div>
<div><slot name="b" /></div>
</template>
<div id="shadowhost">
<iframe src="data:text/html,<button onclick='this.innerText+=`!`'>!</button>"
slot="a" height=40px ></iframe>
</div>
<button onclick="ifr.slot= (ifr.slot=='a') ? 'b' : 'a';">swap</button>
<script>
document.querySelector('#shadowhost').attachShadow({mode: 'open'}).appendChild(
document.querySelector('template').content
);
ifr=document.querySelector('iframe');
</script>
In response to the bounty #djechlin placed on this question, I have forked the jsfiddle posted by #matt-h and have come to the conclusion that this is still not possible.
http://jsfiddle.net/gr3wo9u6/
//this does not work, the frames reload when appended back to the DOM
function swapFrames() {
var w1 = document.getElementById('wrap1');
var w2 = document.getElementById('wrap2');
var f1 = w1.querySelector('iframe');
var f2 = w2.querySelector('iframe');
w1.removeChild(f1);
w2.removeChild(f2);
w1.appendChild(f2);
w2.appendChild(f1);
//f1.parentNode = w2;
//f2.parentNode = w1;
//alert(f1.parentNode.id);
}

Make iframe listen to same event as parent and synchronize using jquery

I have two iframes in an html page in the same domain
<body>
<table border="1" width="100%" height="100%">
<tr>
<th><iframe class="isiframe" width="100%" height="100%" src="/example"></iframe></th>
<th><iframe class="isiframe" width="100%" height="100%" src="/example"></iframe></th>
</tr>
</table>
</body>
I have given the click event for all the a tag in the webpage inside the iframe
$('a').bind('click', function(e){
var path = $(this).getPath();
var ahash={
'path':path
};
if (getFrameElement())
window.parent.document.Aaddevent(e, ahash);
});
The "path" in the click event gives the path of the clicked a tag (eg. html > body > div#bar > ul#abc.def.ghi > li#foo). The getFrameElement() returns the frame which is clicked. Now what i want to do is use this path and trigger the click event in other iframe
I have defined sendevent function from where the other iframe gets the event of the parent iframe and triggers the same event as parent and synchronize.
document.sendevent=function(e, ahash){
var iframes= parent.document.getElementsByTagName('iframe');
for (var i= iframes.length; i--;) {
var iframe= iframes[i];
if(iframe){
$(ahash.path).trigger('click');
}
}
};
This is how i want to do and make the iframe work, follow the path of the parent iframe clicked element and then trigger the click event to make other iframe synchronize with the parent iframe using the path
The click event is not getting triggered inside the sendevent function but i am getting the path of the parent iframe clicked element when i do console.log(ahash .path) inside the sendevent function. How can i make this method work or something similar like that. Please suggest me some solution how to do this.
You cannot follow links using $("a").trigger("click"). You can use location.href = $("a").attr("href"). If you are simply trying to navigate to the same url in both frames don't bother with .getPath(), just pass the href. In your parent page, use this to bind the links in first frame to also navigate the second frame:
$("iframe:first").contents().find("a[href]").click(function() {
$("iframe:last", top.document)[0].contentWindow.location.href = this.href;
});
Edit: In IE and newer versions of FireFox and Opera, you can use the native DOM method .click() to simulate an actual click on the link. Chrome doesn't support it yet, but probably will eventually. To use .getPath() in order to find and click the link, try this in the parent page:
$("iframe:first").load(function() {
$(this).contents().find("a[href]").click(function() {
$("iframe:last", top.document).contents().find($(this.getPath())[0].click();
});
});

Change iframe source from another iframe

Ok, I have 2 iframes inside a parent page (for whatever reason).
I have a navigation menu on parent page, which changes the source of iframe #1...
iFrame #1's job, is to display ANOTHER navigation menu... Like a subnavigation menu...
Now, how can I upon clicking an li inside iFrame #1, change the source of iframe #2? They're both on the same parent page...
Aside from failing miserably, I also get a warning from Chrome's Dev tools -
Unsafe JavaScript attempt to access frame with URL file:///C:/website/index.html from frame with URL file:///C:/website/news/navigator.html. Domains, protocols and ports must match.
Here's some code to make things slightly clearer:
The HTML
<!-- HTML for the parent page itself -->
<iframe id="frameone" src=""></iframe>
<iframe id="frametwo" src=""></iframe>
<button onclick="onenav('test.html')">Change 1st frame</button>
<!-- The following is the HTML that is loaded inside "frameone" -->
<button onclick="twonav('test2.html')">Change 2nd frame</button>
// Javascript
var one = document.getElementById('frameone');
var two = document.getElementById('frametwo');
function onenav(x){
one.src = x;
}
function twonav(y){
two.src = y;
}
To me, this makes sense, since this is all being executed on the parent page... On loading, I query the dev tools and I can see that both, 'one' and 'two' have frame elements... The first button works, the second one, doesn't...
Works for me when using parent.twonav
DEMO
var links = [
'javascript:\'<button onclick="parent.twonav(1)">Change 2nd frame</button>\'',
'javascript:\'Hello\''
];
var one, two;
window.onload=function() {
one = document.getElementById('frameone');
two = document.getElementById('frametwo');
}
function onenav(idx) {
one.src=links[idx];
}
function twonav(idx) {
two.src=links[idx];
}
How did you try to change the iframe source?
parent.document.getElementById('2').src = "the new url";
Did you try something like this? I assumed from your message that the id of the 2nd iframe is 2.

Categories