Loops in Javascript / monitoring objects for updates [duplicate] - javascript

This question already has answers here:
iFrame src change event detection?
(7 answers)
Closed 8 years ago.
I have an iframe. I want to create a loop in Javascript that monitors the iframe's URL. So what I want is something like this:
while(1){
if(iframe.src == "foo"){
iframe.src = "bar"
}
}
What's the correct way to do this (ideally without jQuery etc)?

If you have an infinite loop you have to stop it manually using break:
while (1) {
if(...) {
...
break; //exit loop
}
}
Is this what you wanted to ask? Feel free to ask any further question.
Edit:
The solution I would choose is creating an own event to listen for and a function to trigger the event if needed:
var iframeSrcChangeEvt = new Event("iframeSrcChanged"); //create event
document.querySelector("iframe").addEventListener("iframeSrcChanged",function() { //add event listener to the iframe
this.src = "bar"; //change src as you need it
this.removeEventListener("iframeSrcChanged"); //remove listener if fired
clearInterval(monitorIframe); //stop monitoring the iframe
});
var monitorIframe = setInterval(function() { //set an interval to monitor the iframe
var iframe = document.querySelector("iframe");
if(iframe.src == "foo") {
iframe.dispatchEvent(iframeSrcCHangeEvt); //fire event
}
},500);
I think this solution is better because you are able to add more than one iframe to monitor if you adapt that code.

Related

add an event listener to an element with javascript [duplicate]

This question already has answers here:
Cross domain iframe issue
(5 answers)
Adding click event handler to iframe
(2 answers)
Closed 4 years ago.
Through a script tag I've inserted on an external site, I am trying to load in some javascript which iframes a widget I am hosting on a webpage,
I only want the small launcher icon iFramed initially and then when its opened, iFrame the entire chat window when it's expanded. As Iframing the whole thing takes up a lot of the external site and means everything behind is isnt reachable!
My thought was to have a small iframe initialy and then when it's clicked, increase it's size to the entire window and then while doing so, add an element in the area where the launcher is to then close it when pressed and reduce the iframe size again! hacky I know but i dont know how else I can do this?
What you can see is me creating an iframe, and trying to give it an id
of 'ifrm' with the line:
the code so far: ifrm.setAttribute("id", "ifrm");
. AND then try to change the iframes CSS or append a new one? BUT this doesnt call the function when clicked so i may
have the setting of the ID / calling it wrong?
Then how would I append an element? sorry ive probably gone the wrong way about this.
prepareFrame();
function prepareFrame() {
console.log("yes this consoles inside of prepareFrame")
var ifrm = document.createElement("iframe");
ifrm.setAttribute("src", "https://5efae1b1.ngrok.io");
ifrm.style.width = "100px";
ifrm.style.height = "100px";
ifrm.style.position="fixed";
ifrm.style.right="0";
ifrm.style.bottom="0";
ifrm.style.border="0";
ifrm.setAttribute("id", "ifrm");
document.body.appendChild(ifrm);
document.getElementById("ifrm").addEventListener("click", function(){click1(1);}, false);
}
function click1() {
alert("calling");
document.getElementById("ifrm").style.backgroundColor = '#ff0000';
colorcheck = document.getElementById("ifrm").style.backgroundColor;
console.log('colour check' + colorcheck);
};
Thanks so much if you can help!
Instead of doing this:
document.getElementsByTagName("iframe")[0].setAttribute("id", "ifrm");
Try this at the beginning of your iframe creation:
var ifrm = document.createElement("iframe");
ifrm.setAttribute('id', 'ifrm'); // assign an id
add ifrm.contentDocument.addEventListener("click", function(e){click1(e)}, false) to inside the prepareFrame function, this will then call the click1 function.

Firefox extension to access DOM (with jQuery) [duplicate]

This question already has an answer here:
FireFox extension: How to access page element via jQuery?
(1 answer)
Closed 8 years ago.
I'm trying to manipulate the HTML of a page using my extension and jQuery.
In this simple test, I'm trying to first load jQuery and then replace all h1's to "Hello", like this: $("h1").html("Hello");
See this jsfiddle: http://jsfiddle.net/37vxJ/ (minus the jQuery part:)
var myExtension = {
init: function() {
// The event can be DOMContentLoaded, pageshow, pagehide, load or unload.
if(gBrowser) gBrowser.addEventListener("DOMContentLoaded", this.onPageLoad, false);
},
onPageLoad: function(aEvent) {
var doc = aEvent.originalTarget; // doc is document that triggered the event
setTimeout(function(){
//alert("page is loaded \n" +doc.location.href);
$("h1").html("Hello");
}, 1000);
}
}
window.addEventListener("load", function load(event) {
//remove listener, no longer needed
window.removeEventListener("load", load, false);
myExtension.init();
},false);
How can I make this work?
If I uncomment: //alert("page is loaded \n" +doc.location.href);
The extension will print out the URL (after 1 second)
You are trying to use jQuery in the wrong context.
Change
$("h1").html("Hello");
to
doc.defaultView.wrappedJSObject.$("h1").html("Hello");
Use firebug. it is the best for me.
You can find it here:
https://addons.mozilla.org/fr/firefox/addon/firebug/
UPDATE:
There is a powerful service such as there is a reverse engineering to inspect DOM : Just , click on the blue arrow (mentionned on the picture) , Enter mouse on your Element ,And you will get a synchronization between the GUI and DOM .
Modern versions of Firefox have built in Console, Inspector, Debugger, Profile and Network tracking. Simplyn click on Menu->Developer and select the tool you need
Alternatively use Firebug as recommended in another answer.

Javascript code only working after page refresh and not first viewing [duplicate]

This question already has answers here:
jQuery: document ready fires too early for my requirements
(6 answers)
Closed 8 years ago.
i am using a bit of javascript that checks all of my images for their width and adds a class depending.
It looks like so:
$(document).ready(function(){
// check each image in the .blogtest divs for their width. If its less than X make it full size, if not its poor and keep it normal
var box = $(".blogtest");
box.find("img.buildimage").each(function() {
var img = $(this), width = img.width();
if (width >= 700) {
img.addClass("buildimage-large");
} else if (width < 700) {
img.addClass("buildimage-small");
}
});
});
The issue is, the images dont have a class added to them when you first visit the page, instead they only work when you refresh the page.
Any fix for this?
You need to use the load handler because when the ready handler is triggered the image might not be loaded so the width will be 0 first time, in the second time the image might be cached in the browser making to be loaded faster so when the ready handler is triggered the image might be already loaded so it is working
$(document).ready(function () {
// check each image in the .blogtest divs for their width. If its less than X make it full size, if not its poor and keep it normal
var box = $(".blogtest");
box.find("img.buildimage").on('load', function () {
var img = $(this),
width = img.width();
if (width >= 700) {
img.addClass("buildimage-large");
} else if (width < 700) {
img.addClass("buildimage-small");
}
}).filter(function () {
//if the image is already loaded manually trigger the event
return this.complete;
}).trigger('load');
});
But an additional point to be kept in mind is, by the time the ready handler is triggered if the image is already loaded then the registered load handler will not get triggered so after registering the event handler we need to filter out the images which are already loaded and then manually trigger the load event so that for those images the load event will get triggered
jQuery's .ready handler does not wait for external things like stylesheets or images to load:
In cases where code relies on loaded assets (for example, if the dimensions of an image are required), the code should be placed in a handler for the load event instead.
A load event handler in jQuery looks something like this:
$(document).on('load', function() {
// Your code here
});
The reason it worked on page refresh was probably due to the browser caching the images (and thus they're ready before the browser has finished parsing the HTML.

Javascript - Input change events inside iframes

Is it possible to detect input change events inside an iframe?
The code needs to be pure Javascript and sit outside the iframe. Everytime I type in an input field INSIDE the iframe, the function needs to fire - is this possible??
Try this code:
window.onload = function() {
var iframe = document.getElementsByTagName('iframe')[0];
iframe.onload = function() {
var input = iframe.contentDocument.getElementsByTagName('input')[0];
input.addEventListener('keypress', function() {
// wait until key is entered into input box
setTimeout(function() {
console.log(input.value);
}, 10);
}, false);
};
};
If you are working on the same domain you have access to the iframe.
document.getElementById('yourIframe').contentWindow.document.findElementsByTagName('input')[0].onkeyup = function () {
console.log('Input has changed.');
};
If you are on a different domain you best bet is the postMessage API desribed here: http://davidwalsh.name/window-postmessage
The consequence for this solution is, you'll have to write JS on both sides, the iframe and the parent frame.
document.getElementById('rw_iframe').contentWindow.document.getElementById("fieldID").onchange = function () {
};
Using jquery changes the current context, as long as you use js to attach an event to iframe elements, it will work

Set focus on iframe in Chrome

I have an iframe (id: 'chat') with designMode='on' in Chrome.
On Enter keypress event I call the function send(), which takes the iframe contents and writes it to a socket. My problem is that when clearing the iframe, I lose focus.
How to do I set the focus so I can continue to type text in the iframe?
function send(){
var $iframe = $('#chat');
var text = $iframe.contents().text() + "\n";
socket.send(text);
// When this is done, the focus is lost
// If commented, the focus will not be lost
$iframe.contents().find('body').empty();
// My different failed attempts to regain the focus
//$iframe.focus();
//$iframe.contents().focus();
//$iframe.contents().find('body').focus();
//$iframe.contents().find('body').parent().focus();
//$iframe[0].contentWindow.focus();
// I've also tried all the above with timers
//setTimeout( function(){ $('#chat').contents().focus(); }, 100);
}
I've tried many of the solutions on other questions, but none seems to work.
The trick is to first set focus on the body and then create a Range.
var win = iframe.contentWindow;
var range = win.document.createRange();
range.setStart(win.document.body, 0);
range.setEnd(win.document.body, 0);
win.document.body.focus();
win.getSelection().addRange(range);
This question has been answered here
Basically, if you are not refreshing the iframe you could use:
$iframe[0].contentWindow.focus();
Note that I'm grabbing the underlying iframe DOM object.
I have tried below solution it works in all browser (IE/Chrome/Firefox)
Context: I want to focus the iframe all the time.
function IFocus() {
var iframe = $("#iframeId")[0];
iframe.contentWindow.focus();
};
window.setInterval(IFocus, 300);
Hope it helps, if any one in need...
I tested this solution with Chrome. I originally posted it in Setting focus to iframe contents.
Here is code to create an iframe using jQuery, append it to the document, poll it until it is loaded, then focus it. This is better than setting an arbitrary timeout which may or may not work depending on how long the iframe takes to load.
var jqueryIframe = $('<iframe>', {
src: "http://example.com"
}),
focusWhenReady = function(){
var iframe = jqueryIframe[0],
doc = iframe.contentDocument || iframe.contentWindow.document;
if (doc.readyState == "complete") {
iframe.contentWindow.focus();
} else {
setTimeout(focusWhenReady, 100)
}
}
$(document).append(jqueryIframe);
setTimeout(focusWhenReady, 10);
The code for detecting when the iframe is loaded was adapted from Biranchi's answer to How to check if iframe is loaded or it has a content?

Categories

Resources