Javascript trigger function when iframe has loaded - javascript

I am creating an iFrame via an object instance, when the iFrame loads I need to trigger a method from the original object, and be able to retrieve the content of the iframe back in the object. At the moment "up" apparently does not exist.
function iFrame() {
var Id="1234";
var d = document.createElement('DIV');
d.innerHTML = '<iframe id="'Id+'" name="'+Id+'" onload="up('+Id+');"></iframe>';
document.body.appendChild(d);
obj=this;
var i = document.getElementById(this.frameId);
i.up = (function(obj){obj.iFrameOnload()})(obj);
}
iFrame.prototype.iFrameOnload=function(id) {
d = document.getElementById(id).contentWindow.document;
alert(d.body.innerHTML);
}

Instead of putting plain HTML inside of the div, you should actually create that iframe using DOM directly. This gives you several benefits:
var frame = document.createElement('iframe');
// set id and name attributes directly (although you don’t actually need them)
frame.id = '1234';
frame.name = '1234';
// set frame source (you probably want to set this)
frame.src = '';
// register event listener for the `load` event
frame.addEventListener('load', function () {
// event handler here
var d = this.contentWindow.document;
alert(d.body.innerHTML);
}, false);
document.body.appendChild(frame);
As you can see, there is no need to ask the DOM again to get the iframe element via an ID or something. You created it directly after all, so you already have a reference to it.

your code there is a little messed up. allow me suggest something else:
include jQuery:
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
and then:
<script type="text/javascript">
$(function(){
// create the iframe
var url = 'http://www.google.com';
var iframe_html = '<iframe src="' + url + '" id="iframe"></iframe>';
$('body').append(iframe_html);
// bind load event
$('#iframe').load(function(){
// on load code here
});
});
</script>
hope that helps

You can create a global function up():
function up (iframe_element) {
alert("In up() function");
}
And call it with the 'this' parameter
d.innerHTML = '<iframe id="'Id+'" name="'+Id+'" onload="up(this);"></iframe>';
Full JS-code is in that case:
function up (iframe_element) {
alert("In up() function");
}
function iFrame() {
var Id="1234";
var d = document.createElement('DIV');
d.innerHTML = '<iframe id="'Id+'" name="'+Id+'" onload="up(this);"></iframe>';
document.body.appendChild(d);
}

Related

Set javascript variable from one iframe to another

Trying pass variable from one iframe to another. Sound weird but I made a picture to make it clear:
My first try to add new srcrip to the new iframe. Looks like its work, but new variable undefined.
var creativeFrame = parentDocument.getElementById('iframe2');
var creativeWindow = parentDocument.getElementById('iframe2').contentWindow;
var creativeDocument = creativeFrame.document;
var myFunction = function() {
var iFrameHead = creativeFrame.document.getElementsByTagName("head")[0];
var myscript = creativeBody.createElement('script');
myscript.type = 'text/javascript';
myscript.text = 'var a = 2';
iFrameHead.appendChild(myscript);
};
if(creativeFrame.addEventListener) {
creativeFrame.addEventListener('load', myFunction, true);
} else if(creativeFrame.attachEvent) {
creativeFrame.attachEvent('onload', myFunction);
}
</script>
Window.postMessage() is the recommended way to pass data from one Window object (tab, window, iframe...) to another. Minimal use case:
An event listener must be present in the script of the iframe: window.addEventListener('message', console.log);
The parent window, given a window reference to the iframe, can then send message to the iframe: myIframe.postMessage('hello world', '*')

Appending a button on a div after div loads in the dom

I am trying to access an div (or here a tr tag) on which i want to append a button . But i am unable to access the tr tag because its loading after sometime and is not present in the DOM at that moment and getting error .
how to access a tag after loading something on the DOM
<script>
var btn = document.getElementById('btnn');
var tab = document.getElementsByClassName("scope")[0];
tab.append(btn)
</script>
I think your document.getElementById code should only be executed after everyting has been loaded. You could add an "load" Eventlistener and put your code inside it.
window.addEventListener("load", function(){
var btn = document.getElementById('btnn');
var tab = document.getElementsByClassName("scope")[0];
tab.append(btn)
});
By the way: I always use "defer" for my includes, like this:
<script src="{{ asset('/general/js/local.js') }}" defer></script>
This makes sure the "load" event will only be triggered after all includes have been loaded.
You could watch the DOM using the MutationObserver API. If the element you're observing is added, you could then apply your other code (e.g., append a button).
Basic Example:
let watchDOM = (function(){
let mo = window.MutationObserver;
return function(obj, callback){
if (!obj || !obj.nodeType === 1) {
return;
}
if (mo) {
let obs = new mo(function(mutations, observer) {
callback(mutations);
});
obs.observe(obj, { childList:true, subtree:true });
}
else if (window.addEventListener){
obj.addEventListener('DOMNodeInserted', callback, false);
obj.addEventListener('DOMNodeRemoved', callback, false);
}
}
})();
watchDOM(document.body, function(e) {
// This will notify you if a new DIV is added.
if (e[0].addedNodes[0].tagName === "DIV") {
// If the DIV is added, you can then take some action here.
// For example, you could append your button here.
console.log("div added");
}
});
// This adds a new DIV after 3 seconds of running the script
setTimeout(function() {
let newDiv = document.createElement("div");
document.body.appendChild(newDiv);
}, 3000);
Is this DIV getting created in the response of an AJAX call. If that is the case then you need to call you your button appending logic once the response of AJAX call has been received.
OR use this:
<script type="text/javascript">
document.addEventListener("DOMContentLoaded", function(event) {
// - Code to execute when all DOM content is loaded.
// - including fonts, images, etc.
});
</script>

Variable Scope of function inside function jquery

I have this jquery function extend, but the exec command for the redColorBtn does not seem to work. If I move the var iframeDocument definition to inside the redColorBtn function, then it works. But, I can't wrap my head around why this would happen. I thought it would be because of variable scope, but then the iframe definition should also not be working outside the redColorBtn click function. Does anyone know?
$.extend({
handleToolbarEvents: function(iframeDocumentId) {
var iframe = document.getElementById(iframeDocumentId);
var iframeDocument = iframe.contentWindow.document;
var redColorBtn = document.getElementById('rte-redColorBtn-' + iframeDocumentId);
$(redColorBtn).click(function() {
var command = $(this).val();//foreColor
iframeDocument.execCommand(command, false, "red");
});
$('.rte-button').click(function() {
var command = $(this).val();
var iframeID = $(this).closest('iframe[class="rte-iframe"]');
var iframeDocument = iframe.contentWindow.document;
iframeDocument.execCommand(command, null, null);
});
}
});
i have once's the same problem that i add the click event but it doesn't work. It can be about if you are adding that redColorBtn dynamically it might be your problem. you can try redColorButton.bind('click', function(){}); I don't know why it but it worked for me.
Hope it works.

Changing value of element in a new window [duplicate]

I open a new window using the following code:
purchaseWin = window.open("Purchase.aspx","purchaseWin2", "location=0,status=0,scrollbars=0,width=700,height=400");
I want to access the dom tree of the purchaseWin, e.g.
purchaseWin.document.getElementById("tdProduct").innerHTML = "2";
It doesn't work. I can only do this:
purchaseWin.document.write("abc");
I also try this and it doesn't work too:
$(purchaseWin.document).ready(function(){
purchaseWin.$("#tdProduct").html("2");
});
What should I do?
With jQuery, you have to access the contents of the document of your child window:
$(purchaseWin.document).ready(function () {
$(purchaseWin.document).contents().find('#tdProduct').html('2');
});
Without libraries, with plain JavaScript, you can do it this way:
purchaseWin.onload = function () {
purchaseWin.document.getElementById('tdProduct').innerHTML = '2';
};
I think that the problem was that you were trying to retrieve the DOM element before the child window actually loaded.
Maybe the load event of jQuery works for you as this worked for me in a similar Problem, whereas the ready event did not work:
$(purchaseWin).load(function(){
purchaseWin.$("#tdProduct").html("2");
});
You cannot access the document of a child window if you load a page that does not belong to the domain of the parent window. This is due to the cross-domain security built into Javascript.
(function() {
document.getElementById("theButton").onclick = function() {
var novoForm = window.open("http://jsbin.com/ugucot/1", "wFormx", "width=800,height=600,location=no,menubar=no,status=no,titilebar=no,resizable=no,");
novoForm.onload = function() {
var w = novoForm.innerWidth;
var h = novoForm.innerHeight;
novoForm.document.getElementById("monitor").innerHTML = 'Janela: '+w+' x '+h;
};
};
})();

How can I access the dom tree of child window?

I open a new window using the following code:
purchaseWin = window.open("Purchase.aspx","purchaseWin2", "location=0,status=0,scrollbars=0,width=700,height=400");
I want to access the dom tree of the purchaseWin, e.g.
purchaseWin.document.getElementById("tdProduct").innerHTML = "2";
It doesn't work. I can only do this:
purchaseWin.document.write("abc");
I also try this and it doesn't work too:
$(purchaseWin.document).ready(function(){
purchaseWin.$("#tdProduct").html("2");
});
What should I do?
With jQuery, you have to access the contents of the document of your child window:
$(purchaseWin.document).ready(function () {
$(purchaseWin.document).contents().find('#tdProduct').html('2');
});
Without libraries, with plain JavaScript, you can do it this way:
purchaseWin.onload = function () {
purchaseWin.document.getElementById('tdProduct').innerHTML = '2';
};
I think that the problem was that you were trying to retrieve the DOM element before the child window actually loaded.
Maybe the load event of jQuery works for you as this worked for me in a similar Problem, whereas the ready event did not work:
$(purchaseWin).load(function(){
purchaseWin.$("#tdProduct").html("2");
});
You cannot access the document of a child window if you load a page that does not belong to the domain of the parent window. This is due to the cross-domain security built into Javascript.
(function() {
document.getElementById("theButton").onclick = function() {
var novoForm = window.open("http://jsbin.com/ugucot/1", "wFormx", "width=800,height=600,location=no,menubar=no,status=no,titilebar=no,resizable=no,");
novoForm.onload = function() {
var w = novoForm.innerWidth;
var h = novoForm.innerHeight;
novoForm.document.getElementById("monitor").innerHTML = 'Janela: '+w+' x '+h;
};
};
})();

Categories

Resources