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.
Related
I want to load stackoverflow page and then raise the alert, strictly one after the other, without using frameworks like jQuery etc.
I have gone through the answers here and visited this too.
I ran the following in browser console. The page loads but the alert is not raised. I am using chrome in windows 8.1.
Try #1:
window.location.href = 'https://stackoverflow.com/';
window.onload = function () { alert("It's loaded!") }
Try #2:
window.location.href = 'https://stackoverflow.com/';
if(document.readyState === "complete") {
//Already loaded!
window.onload = function () { alert("It's loaded!") }
}
else {
//Add onload or DOMContentLoaded event listeners here: for example,
window.addEventListener("onload", function () {/* your code here */}, false);
//or
//document.addEventListener("DOMContentLoaded", function () {/* code */}, false);
}
Try #3:
window.location.href = 'https://stackoverflow.com/';
var everythingLoaded = setInterval(function() {
if (/loaded|complete/.test(document.readyState)) {
clearInterval(everythingLoaded);
alert("It's loaded!");
}
}, 1000);
Try #4:
Tried setTimeout() too but doesn't work either.
I have tried above examples with window.location.replace() also.
How do I make this work?
P.S: I am novice with javascript. The above codes are not mine but I am just trying to work them out. I don't claim to have understood them completely either.
As Barmar pointed out this is not possible. The new page load will remove all JavaScript from the old page. Some alternatives are:
You can open the new page or in a new tab using the window.open api and attach an event handler.
You can load the page inside a frame (if it doesn't have any restrictions preventing that) and add a load event to the frame.
You can load the page using XMLHttpRequest (or a library of your choice) and insert the result into a <div> though not all of it will probably work.
You don't say what you want to do once the page has loaded. In most cases (generally unless you own the second page) it will not be possible to access any information on the second page.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
jQuery callback on image load (even when the image is cached)
So the .load() method has been deprecated in jQuery. load() is a shortcut for `bind('load', function).
From http://api.jquery.com/load-event/:
Caveats of the load event when used with images
A common challenge developers attempt to solve using the .load()
shortcut is to execute a function when an image (or collection of
images) have completely loaded. There are several known caveats with
this that should be noted. These are:
It doesn't work consistently nor reliably cross-browser It doesn't
fire correctly in WebKit if the image src is set to the same src as
before It doesn't correctly bubble up the DOM tree Can cease to fire
for images that already live in the browser's cache`
How does one perform a function on image load consistently? My Current code looks like so:
$(newImage).bind('load', function() {
createSlices(slide);
});
However after reading the docs (although I haven't noticed any problems) I am worried it may not fire for some users.
Try this plugin man: called waitforimages plugin: https://github.com/alexanderdickson/waitForImages (scroll down the link you will see various advanced use) - demo http://jsfiddle.net/FZ7Xy/
Hope it fits the need :)
Code
$('selector').waitForImages(function() {
// All descendant images have loaded, now slide up.
$(this).slideUp();
});
var img = new Image();
img.onload = function() {
}
img.src= src-image
the above code works on all browsers and even without jquery.
You're right to worry, IE7/8 in particular will sometimes fail to fire the load event if the image is cached.
One technique is to immediately check if the image is complete after binding the load event:
$(newImage).bind('load error', function() {
createSlices(slide);
});
// check if the image is immediately complete (cached)
if (newImage.complete || typeof newImage.complete === 'undefined') {
createSlices(slide);
}
I've tested with success in:
IE 7/8/9/10
FF4+
Chrome (latest)
Safari 5+
There is a great library that handles exactly this: https://github.com/desandro/imagesloaded
I've used it in production and it works wonderfully. Extremely reliable, not a single complaint.
This is my code:
document.addEventListener('load', function () {
alert(document.getElementsByTagName("DIV").length);
}, false);
//'load' event above doesn't show any response, alert isn't showing
alert(document.getElementsByTagName("DIV").length);
// this alert returns 0 it looks like it is called before the page DOM has loaded
window.onload = function() {
alert(document.getElementsByTagName("DIV").length);
};
//returns 0, what the... it seems DOM hasn't loaded also
// but only on some sites, here on stackoverflow and youtube it works,
//but on google.com and many other websites (pcworld.com) shows 0
The same situation in latest stable and alpha Operas.
I suggest you simply do
window.addEventListener('load', function(){}, false)
like you would in a normal script. You could use opera.addEventListener('BeforeEvent.load', ...) but that might not fire if the page's scripts do not listen for load events in some Opera versions.
Some other background reading:
window.onload vs document.onload
addEventListener("input", callback) doesn't work in opera?
I have a Firefox extension that detects whenever a page loads in the browser and returns its window and document. I want to attach some events (that launch functions in my addon's overlay) to elements in the page, but I don't know how to do this in a way that's safe.
Here's a code sample:
var myExt = {
onInit: function(){
var appcontent = document.getElementById("appcontent");
if(appcontent){
appcontent.addEventListener("DOMContentLoaded", this.onPageLoad, true);
}
},
onPageLoad: function(e){
var doc = e.originalTarget;
var win = doc.defaultView;
doc.getElementById("search").focus = function(){
/* ... 'Some privelliged code here' - unsafe? ... */
};
}
};
So can anyone tell me what's the safe way to add these events/interact with the page's DOM?
Thanks in advance!
I think that you want to listen to the focus event, not replace the focus() function:
doc.getElementById("search").addEventListener("focus", function(event)
{
if (!event.isTrusted)
return;
...
}, false);
Usually, there is fairly little that can go wrong here because you are not accessing the page directly - there is already a security layer (which is also why replacing the focus() method will have no effect). You can also make sure that you only act on "real" events and not events that have been generated by the webpage, you check event.isTrusted for that like in the example code. But as long as you don't unwrap objects or run code that you got from the website, you should be safe.
I have a gallery I quickly coded up for a small site, and under Firefox 3 and Safari 3 works fine. But when I test on my old best friend IE7, it seems to not fire the imageVar.onload = function() { // code here }.. which I want to use to stop the load effect and load the image.
Please bear in mind...
I know the thumbnails are just scaled down version of the larger images. When the images are finalised by the client I am going to create proper thumbnails.
This is my first attempt to try and get out of procedural JavaScript for the most part.. so please go easy and kindly let me know where my code sucks!
For successful use of Image.onload, you must register the event handler method before the src attribute is set.
Related Information in this Question:
Javascript callback for Image Loading
Cross browser event support is not so straightforward due to implementation differences. Since you are using jQuery at your site, you are better off using its events methods to normalize browser support:
instead of:
window.load = function(){
//actions to be performed on window load
}
imageViewer.image.onload = function(){
//actions to be performed on image load
}
Do:
$(window).load(function(){
//actions to be performed on window load
});
$(imageViewer.image).load(function(){
//actions to be performed on image load
});
Just to add to the suggestion by Eran to use the jQuery's built in event handlers you can run code when the document is loaded and the DOM is created but before the images are downloaded with:
$(document).ready(function(){
//your code
});