XMLHttpRequest from Firefox Extension - javascript

I'm using XMLHttpRequest to exchange data between server and Firefox extension I'm developing. Unfortunately, those requests seem somehow connected with the currently open page - if I try to issue request while the current tab is closing, it will fail with an error. How can I make my requests originate from the extension itself, independently of what's going on in tabs?
EDIT: Here is the code that reproduces this problem. It's run as the main extension body (I based my design on the "Hello world" tutorial from http://kb.mozillazine.org/Getting_started_with_extension_development, so no Add-on SDK). This means that it's executed in the same place as the code from "overlay.js" in above tutorial.
function createXMLHttpRequest() {
return Components.classes["#mozilla.org/xmlextras/xmlhttprequest;1"]
.createInstance(Components.interfaces.nsIXMLHttpRequest);
}
function issueRequest() {
var req = createXMLHttpRequest();
req.open("GET", "http://google.com", true);
req.addEventListener("load", function(event) {
alert("SUCCES");
});
req.addEventListener("error", function(event) {
alert("ERROR");
});
req.send();
};
window.addEventListener("DOMContentLoaded", function(event) {
issueRequest();
var doc = event.originalTarget;
var win = doc.defaultView;
win.addEventListener("unload", function(event) {
issueRequest();
});
});
This results in "SUCCESS" after opening of new tab, and "ERROR" after closing it. I would prefer to have two SUCCESSES.

If that script is running in a browser window overlay then you attached your DOMContentLoaded handler to the wrong node - you will only get notified when the browser window itself loads. Consequently, your unload handler waits for the browser window to the closed, you probably intended to wait for a tab to be closed. The correct code would look like this:
// Wait for the browser window to load before doing anything
window.addEventListener("load", function() {
// Attach a listener to the tabbrowser to get notified about new pages
window.gBrowser.addEventListener("DOMContentLoaded", function(event) {
issueRequest();
var doc = event.originalTarget;
var win = doc.defaultView;
win.addEventListener("unload", function(event) {
issueRequest();
});
}, false);
}, false)

Related

Detect print events from iFrame

I am trying to build a print solution which programmatically prints PDF documents using URLs and fire an event after printing.
I am using the "matchMedia" event listener below to test with Chrome (v54). For IE and Firefox, I plan to listen to the "onbeforeprint" and "onafterprint" of the same iframe contentWindow object.
Here is how I invoke the print. The dojo function is just an xhr wrapper.
dojoRequest(url, {
handleAs: 'blob'
}).then(function (blob) {
var src = URL.createObjectURL(blob);
printFrame = document.createElement('iframe');
printFrame.id = 'print-frame';
// printFrame.style.display = 'none';
printFrame.src = src;
document.body.appendChild(printFrame);
var mediaQueryList = printFrame.contentWindow.matchMedia('print');
mediaQueryList.addListener(function (mql) {
console.log('print event', mql);
debugger;
});
setTimeout(function () {
printFrame.contentWindow.print();
}, 0);
});
This works well except that the "print event" event never fires. I would expect it to fire once when showing the "print preview" window and again after clicking the "print" button.
I tried registering the same event listener against the main "window" object. It fires when initiating a print manually (from the File menu), but not when initiating the print programmatically using the method described above.
To get events, you must wrap your code inside of onload of iframe, like this:
printFrame.onload = function () {
var mediaQueryList = printFrame.contentWindow.matchMedia('print');
mediaQueryList.addListener(function (mql) {
console.log('print event', mql);
});
setTimeout(function () {
printFrame.contentWindow.print();
}, 0);
};
However, I still think that this approach is really complex and not stable enough for enterprise application.
UPDATE:
Jsfiddle link showing it works on Chrome 54: https://jsfiddle.net/anhhnt/nj851e52/

xmlhttprequest for pdf file works for sync but not async

I'm testing out some code to scrape PDFs from a chrome extension by capturing user-clicked links. Synchronous xmlhttprequest works on links to both html documents and pdfs. However, asynchronous seem to never return. Am I doing something horribly wrong?
Here's a minimal demonstrative example of my content.js in the failing async version:
var links = document.getElementsByTagName("a");
function getlink(link) {
console.log("looking for link");
var x = new XMLHttpRequest();
x.open("GET", link, true);
x.onload = function(e) {
console.log("loaded");
console.log(link);
console.log(x.status);
};
x.onerror = function (e) {
console.error(x.statusText);
};
x.send(null);
}
for (i = 0, len = links.length; i < len; i++) {
var l = links[i]
l.addEventListener("click", function() {
console.log(this.href);
getlink(this.href);
}, false);
};
with that code, when a link to a html document is clicked, it logs, as expected, "looking for link", "loaded," the url, and "200". And that's also what it logs when I rewrite this code to just fetch synchronously (by switching the last argument to the open method to true, and moving all the logging code out of an unload to the calling function.
But when I fetch a pdf asynchronously, it just says "looking for link" and then silence---no error, no response. It does give me a message:
Resource interpreted as Document but transferred with MIME type application/pdf: "[URL TO PDF]".
but I'm not sure if that comes from the javascript link capture, or the ordinary browser click action.
Does anyone have any insight here? Unfortunately, I think I have to do this async...
In synchronous mode the PDF is fetched before the default link event handler sees the click event.
In asynchronous mode the browser first handles the click event and loads the PDF file in current tab, so the original page is destroyed with all its event handlers and callbacks.
Method 1: use a background (event) page script:
define a message listener: chrome.runtime.onMessage in the background page that will fetch the PDF asynchronously
in the click handler send a message with the PDF url using chrome.runtime.postMessage
Method 2: disable the default click behavior:
l.addEventListener("click", function(e) {
e.preventDefault();
//e.stopPropagation(); // may be needed if the page has a custom event handler
//e.stopImmediatePropagation(); // same reason
console.log(this.href);
getlink(this.href);
}, false);
.........
And maybe do the navigation once the PDF is fetched:
function getlink(link) {
.........
x.onload = function(e) {
console.log("loaded");
console.log(link);
console.log(x.status);
window.location.href = link;
};
.........

Javascript code for detecting tab or browser closing [duplicate]

Is there any cross-browser JavaScript/jQuery code to detect if the browser or a browser tab is being closed, but not due to a link being clicked?
If I get you correctly, you want to know when a tab/window is effectively closed. Well, AFAIK the only way in JavaScript to detect that is to use either onunload or onbeforeunload events.
Unfortunately (or fortunately?), those events are also fired when you leave a site over a link or your browsers back button. So this is the best answer I can give, I don't think you can natively detect a pure close in JavaScript. Correct me if I'm wrong here.
From MDN Documentation
For some reasons, Webkit-based browsers don't follow the spec for the dialog box. An almost cross-working example would be close from the below example.
window.addEventListener("beforeunload", function (e) {
var confirmationMessage = "\o/";
(e || window.event).returnValue = confirmationMessage; //Gecko + IE
return confirmationMessage; //Webkit, Safari, Chrome
});
This example for handling all browsers.
Simple Solution
window.onbeforeunload = function () {
return "Do you really want to close?";
};
<body onbeforeunload="ConfirmClose()" onunload="HandleOnClose()">
var myclose = false;
function ConfirmClose()
{
if (event.clientY < 0)
{
event.returnValue = 'You have closed the browser. Do you want to logout from your application?';
setTimeout('myclose=false',10);
myclose=true;
}
}
function HandleOnClose()
{
if (myclose==true)
{
//the url of your logout page which invalidate session on logout
location.replace('/contextpath/j_spring_security_logout') ;
}
}
//This is working in IE7, if you are closing tab or browser with only one tab
For similar tasks, you can use sessionStorage to store data locally until the browser tab is closed.
The sessionStorage object stores data for only one session (the data is deleted when the browser tab is closed).(W3Schools)
This is my pen.
<div id="Notice">
<span title="remove this until browser tab is closed"><u>dismiss</u>.</span>
</div>
<script>
$("#Notice").click(function() {
//set sessionStorage on click
sessionStorage.setItem("dismissNotice", "Hello");
$("#Notice").remove();
});
if (sessionStorage.getItem("dismissNotice"))
//When sessionStorage is set Do stuff...
$("#Notice").remove();
</script>
I needed to automatically log the user out when the browser or tab closes, but not when the user navigates to other links. I also did not want a confirmation prompt shown when that happens. After struggling with this for a while, especially with IE and Edge, here's what I ended doing (checked working with IE 11, Edge, Chrome, and Firefox) after basing off the approach by this answer.
First, start a countdown timer on the server in the beforeunload event handler in JS. The ajax calls need to be synchronous for IE and Edge to work properly. You also need to use return; to prevent the confirmation dialog from showing like this:
window.addEventListener("beforeunload", function (e) {
$.ajax({
type: "POST",
url: startTimerUrl,
async: false
});
return;
});
Starting the timer sets the cancelLogout flag to false. If the user refreshes the page or navigates to another internal link, the cancelLogout flag on the server is set to true. Once the timer event elapses, it checks the cancelLogout flag to see if the logout event has been cancelled. If the timer has been cancelled, then it would stop the timer. If the browser or tab was closed, then the cancelLogout flag would remain false and the event handler would log the user out.
Implementation note: I'm using ASP.NET MVC 5 and I'm cancelling logout in an overridden Controller.OnActionExecuted() method.
I found a way, that works on all of my browsers.
Tested on following versions:
Firefox 57, Internet Explorer 11, Edge 41, one of the latested Chrome (it won't show my version)
Note: onbeforeunload fires if you leave the page in any way possible (refresh, close browser, redirect, link, submit..). If you only want it to happen on browser close, simply bind the event handlers.
$(document).ready(function(){
var validNavigation = false;
// Attach the event keypress to exclude the F5 refresh (includes normal refresh)
$(document).bind('keypress', function(e) {
if (e.keyCode == 116){
validNavigation = true;
}
});
// Attach the event click for all links in the page
$("a").bind("click", function() {
validNavigation = true;
});
// Attach the event submit for all forms in the page
$("form").bind("submit", function() {
validNavigation = true;
});
// Attach the event click for all inputs in the page
$("input[type=submit]").bind("click", function() {
validNavigation = true;
});
window.onbeforeunload = function() {
if (!validNavigation) {
// -------> code comes here
}
};
});
There is no event, but there is a property window.closed which is supported in all major browsers as of the time of this writing. Thus if you really needed to know you could poll the window to check that property.
if(myWindow.closed){do things}
Note:
Polling anything is generally not the best solution. The window.onbeforeunload event should be used if possible, the only caveat being that it also fires if you navigate away.
Sorry, I was not able to add a comment to one of existing answers, but in case you wanted to implement a kind of warning dialog, I just wanted to mention that any event handler function has an argument - event. In your case you can call event.preventDefault() to disallow leaving the page automatically, then issue your own dialog. I consider this a way better option than using standard ugly and insecure alert(). I personally implemented my own set of dialog boxes based on kendoWindow object (Telerik's Kendo UI, which is almost fully open-sourced, except of kendoGrid and kendoEditor). You can also use dialog boxes from jQuery UI. Please note though, that such things are asynchronous, and you will need to bind a handler to onclick event of every button, but this is all quite easy to implement.
However, I do agree that the lack of the real close event is terrible: if you, for instance, want to reset your session state at the back-end only on case of the real close, it's a problem.
$(window).unload( function () { alert("Bye now!"); } );
onunload is the answer for Chrome. According to caniuse its crossbrowser. But not all browsers react the same.
window.onunload = function(){
alert("The window is closing now!");
}
developer.mozilla.org
These events fire when the window is unloading its content and resources.
For Chrome:
onunload executes only on page close. It doesn't execute even on page refresh and on navigating to a different page.
For Firefox v86.0:
It wouldn't execute at all. Page refresh, navigating away, closing browser tab, closing browser, nothing.
Since no one has mentioned it yet (8+ years later): A WebSocket can be another effective way to detect a closed tab. As long as the tab is open and pointed at the host, the client is able to maintain an active WebSocket connection to the host.
Caveat: Please note that this solution is really only viable for a project if a WebSocket doesn't require any additional significant overhead from what you are already doing.
Within a sensible timeout period (e.g. 2 minutes), the server side can determine that the client has gone away after the WebSocket has disconnected and perform whatever action is desired such as removing uploaded temp files. (In my extremely specialized use-case, my goal was to terminate a localhost app server three seconds after the WebSocket connection drops and all CGI/FastCGI activity terminates - any other keep-alive connections don't affect me.)
I had problems getting the onunload event handler to work properly with beacons (as recommended by this answer). Closing the tab did not appear to trigger the beacon and open tabs triggered it in ways that could potentially cause problems. A WebSocket solved the problem I was running into more cleanly because the connection closes roughly around the same time that the tab closes and switching pages within the application simply opens a new WebSocket connection well within the delay window.
It can be used to alert the user if some data is unsaved or something like that. This method works when the tab is closed or when the browser is closed, or webpage refresh.
It won't work unless the user has not interacted with the webpage, this is a mechanism to fight malicious websites..... there will be no popup unless you atleast make a click or touch on the website window.
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form>
<textarea placeholder = "Write...."></textarea>
</form>
<script type="text/javascript">
window.addEventListener('beforeunload', function (e) {
e.returnValue = '';
});
</script>
</body>
</html>
window.onbeforeunload = function() {
console.log('event');
return false; //here also can be string, that will be shown to the user
}
window.addEventListener("beforeunload", function (e) {
var confirmationMessage = "tab close";
(e || window.event).returnValue = confirmationMessage; //Gecko + IE
sendkeylog(confirmationMessage);
return confirmationMessage; //Webkit, Safari, Chrome etc.
});
//Detect Browser or Tab Close Events
$(window).on('beforeunload',function(e) {
e = e || window.event;
var localStorageTime = localStorage.getItem('storagetime')
if(localStorageTime!=null && localStorageTime!=undefined){
var currentTime = new Date().getTime(),
timeDifference = currentTime - localStorageTime;
if(timeDifference<25){//Browser Closed
localStorage.removeItem('storagetime');
}else{//Browser Tab Closed
localStorage.setItem('storagetime',new Date().getTime());
}
}else{
localStorage.setItem('storagetime',new Date().getTime());
}
});
JSFiddle Link
Hi all, I was able to achieve 'Detect Browser and Tab Close Event' clicks by using browser local storage and timestamp. Hope all of you will get solved your problems by using this solution.
After my initial research i found that when we close a browser, the browser will close all the tabs one by one to completely close the browser. Hence, i observed that there will be very little time delay between closing the tabs. So I taken this time delay as my main validation point and able to achieve the browser and tab close event detection.
I tested it on Chrome Browser Version 76.0.3809.132 and found working
:) Vote Up if you found my answer helpful....
I have tried all above solutions, none of them really worked for me, specially because there are some Telerik components in my project which have 'Close' button for popup windows, and it calls 'beforeunload' event. Also, button selector does not work properly when you have Telerik grid in your page (I mean buttons inside the grid) So, I couldn't use any of above suggestions. Finally this is the solution worked for me.
I have added an onUnload event on the body tag of _Layout.cshtml. Something like this:
<body onUnload="LogOff()">
and then add the LogOff function to redirect to Account/LogOff which is a built-in method in Asp.Net MVC. Now, when I close the browser or tab, it redirect to LogOff method and user have to login when returns. I have tested it in both Chrome & Firefox. And it works!
function LogOff() {
$.ajax({
url: "/Account/LogOff",
success: function (result) {
}
});
}
window.onbeforeunload = function ()
{
if (isProcess > 0)
{
return true;
}
else
{
//do something
}
};
This function show a confirmation dialog box if you close window or refresh page during any process in browser.This function work in all browsers.You have to set isProcess var in your ajax process.
It is possible to check it with the help of window.closed in an event handler on 'unload' event like this, but timeout usage is required (so result cannot be guaranteed if smth delay or prevent window from closure):
Example of JSFiddle (Tested on lates Safari, FF, Chrome, Edge and IE11 )
var win = window.open('', '', 'width=200,height=50,left=200,top=50');
win.document.write(`<html>
<head><title>CHILD WINDOW/TAB</title></head>
<body><h2>CHILD WINDOW/TAB</h2></body>
</html>`);
win.addEventListener('load',() => {
document.querySelector('.status').innerHTML += '<p>Child was loaded!</p>';
});
win.addEventListener('unload',() => {
document.querySelector('.status').innerHTML += '<p>Child was unloaded!</p>';
setTimeout(()=>{
document.querySelector('.status').innerHTML += getChildWindowStatus();
},1000);
});
win.document.close()
document.querySelector('.check-child-window').onclick = ()=> {
alert(getChildWindowStatus());
}
function getChildWindowStatus() {
if (win.closed) {
return 'Child window has been closed!';
} else {
return 'Child window has not been closed!';
}
}
There have been updates to the browser to better tack the user when leaving the app. The event 'visibilitychange' lets you tack when a page is being hidden from another tab or being closed. You can track the document visibility state. The property document.visibilityState will return the current state. You will need to track the sign in and out but its closer to the goal.
This is supported by more newer browser but safari (as we know) never conforms to standards. You can use 'pageshow' and 'pagehide' to work in safari.
You can even use new API's like sendBeacon to send a one way request to the server when the tab is being closed and shouldn't expect a response.
I build a quick port of a class I use to track this. I had to remove some calls in the framework so it might be buggy however this should get you started.
export class UserLoginStatus
{
/**
* This will add the events and sign the user in.
*/
constructor()
{
this.addEvents();
this.signIn();
}
/**
* This will check if the browser is safari.
*
* #returns {bool}
*/
isSafari()
{
if(navigator && /Safari/.test(navigator.userAgent) && /Chrome/.test(navigator.userAgent))
{
return (/Google Inc/.test(navigator.vendor) === false);
}
return false;
}
/**
* This will setup the events array by browser.
*
* #returns {array}
*/
setupEvents()
{
let events = [
['visibilitychange', document, () =>
{
if (document.visibilityState === 'visible')
{
this.signIn();
return;
}
this.signOut();
}]
];
// we need to setup events for safari
if(this.isSafari())
{
events.push(['pageshow', window, (e) =>
{
if(e.persisted === false)
{
this.signIn();
}
}]);
events.push(['pagehide', window, (e) =>
{
if(e.persisted === false)
{
this.signOut();
}
}]);
}
return events;
}
/**
* This will add the events.
*/
addEvents()
{
let events = this.setupEvents();
if(!events || events.length < 1)
{
return;
}
for(var i = 0, length = events.length; i < length; i++)
{
var event = events[i];
if(!event)
{
continue;
}
event[1].addEventListener(event[0], event[3]);
}
}
/**
*
* #param {string} url
* #param {string} params
*/
async fetch(url, params)
{
await fetch(url,
{
method: 'POST',
body: JSON.stringify(params)
});
}
/**
* This will sign in the user.
*/
signIn()
{
// user is the app
const url = '/auth/login';
let params = 'userId=' + data.userId;
this.fetch(url, params);
}
/**
* This will sign out the user.
*/
signOut()
{
// user is leaving the app
const url = '/auth/logout';
let params = 'userId=' + data.userId;
if(!('sendBeacon' in window.navigator))
{
// normal ajax request here
this.fetch(url, params);
return;
}
// use a beacon for a more modern request the does not return a response
navigator.sendBeacon(url, new URLSearchParams(params));
}
}
My approach would be along these lines:
Listen for changes in the url with onpopstate and set a sessionStorage variable with 1
Listen for page load and set that sessionStorage variable to 0
On beforeunload, check if the variable is 0. If so it means that the user is closing and not changing url.
This is still a roundabout way to go, but makes sense to me
As #jAndy mentioned, there is no properly javascript code to detect a window being closed.
I started from what #Syno had proposed.
I had pass though a situation like that and provided you follow these steps, you'll be able to detect it.
I tested it on Chrome 67+ and Firefox 61+.
var wrapper = function () { //ignore this
var closing_window = false;
$(window).on('focus', function () {
closing_window = false;
//if the user interacts with the window, then the window is not being
//closed
});
$(window).on('blur', function () {
closing_window = true;
if (!document.hidden) { //when the window is being minimized
closing_window = false;
}
$(window).on('resize', function (e) { //when the window is being maximized
closing_window = false;
});
$(window).off('resize'); //avoid multiple listening
});
$('html').on('mouseleave', function () {
closing_window = true;
//if the user is leaving html, we have more reasons to believe that he's
//leaving or thinking about closing the window
});
$('html').on('mouseenter', function () {
closing_window = false;
//if the user's mouse its on the page, it means you don't need to logout
//them, didn't it?
});
$(document).on('keydown', function (e) {
if (e.keyCode == 91 || e.keyCode == 18) {
closing_window = false; //shortcuts for ALT+TAB and Window key
}
if (e.keyCode == 116 || (e.ctrlKey && e.keyCode == 82)) {
closing_window = false; //shortcuts for F5 and CTRL+F5 and CTRL+R
}
});
// Prevent logout when clicking in a hiperlink
$(document).on("click", "a", function () {
closing_window = false;
});
// Prevent logout when clicking in a button (if these buttons rediret to some page)
$(document).on("click", "button", function () {
closing_window = false;
});
// Prevent logout when submiting
$(document).on("submit", "form", function () {
closing_window = false;
});
// Prevent logout when submiting
$(document).on("click", "input[type=submit]", function () {
closing_window = false;
});
var toDoWhenClosing = function() {
//write a code here likes a user logout, example:
//$.ajax({
// url: '/MyController/MyLogOutAction',
// async: false,
// data: {
// },
// error: function () {
// },
// success: function (data) {
// },
//});
};
window.onbeforeunload = function () {
if (closing_window) {
toDoWhenClosing();
}
};
};
try this,
I am sure this will work for you.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type='text/javascript'>
$(function() {
try{
opera.setOverrideHistoryNavigationMode('compatible');
history.navigationMode = 'compatible';
}catch(e){}
function ReturnMessage()
{
return "wait";
}
function UnBindWindow()
{
$(window).unbind('beforeunload', ReturnMessage);
}
$(window).bind('beforeunload',ReturnMessage );
});
</script>
Try this. It will work. jquery unload method is depreceted.
window.onbeforeunload = function(event) {
event.returnValue = "Write something clever here..";
};

Opening my page in firefox after installing the addon

HI,
My am trying to open my home page after the firefox restarts for the first time after installation.
For this i am adding the event handler on load page and checks where this event is executed for the first time or not.
window.addEventListener("load", initializeOverlay, false);
But my problem is how to open the page in new tab when the firefox get started. I use
`window.open("https://www.xyz.com/");`
but that opens the page in new window that might even be open in internet explorer.
So is there any way to open the page in new tab in same window which is going to be open.
Thanks
BHAVIK GOYAL
I manage to do something similar using preferences, rather than creating files, etc.
Inside of /defaults/preferences/default.js:
pref("extensions.extension_name.just_installed", true);
pref("extensions.extension_name.post_install_url", "http://www.google.com");
Then inside the main JS file for the add-on:
// Retrieve the preferences.
var prefs;
prefs = Components.classes["#mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefService).getBranch("extensions.extension_name.");
prefs.QueryInterface(Components.interfaces.nsIPrefBranch2);
// If we just installed, open the post-install page and update the preferences.
var just_installed = prefs.getBoolPref("just_installed");
var post_install_url = prefs.getCharPref("post_install_url");
if (just_installed) {
prefs.setBoolPref("just_installed", false);
gBrowser.selectedTab = gBrowser.addTab(prefs.getCharPref("post_install_url"));
}
Only problem is Firefox doesn't reset the preferences saved by an extension after that extension is uninstalled.
I got the answer. We can add the gbrowser.open("http://www.xyz.com/") to open in new tab and this statement has to be executed in new function that is by calling the other event handler function loadedoverlay which is defined as follow:
function loadedOverlay() {
try{
var file = Components.classes["#mozilla.org/file/local;1"].createInstance(Components.interfaces.nsILocalFile);
file.initWithPath(Components.classes["#mozilla.org/file/directory_service;1"].getService( Components.interfaces.nsIProperties).get("ProfD", Components.interfaces.nsIFile).path+"\\initialstart.txt");
if ( file.exists() == true )
{
}
else
{
file.create( Components.interfaces.nsIFile.NORMAL_FILE_TYPE, 420 );
var Website="http://www.emailstationery.com/";
gBrowser.addTab(Website);//This is for new Tab
}
} catch(e) {}
}
The call to this function has to be add in the load event function by adding the code of lines as below:-
var appcontent = document.getElementById("appcontent"); // browser
if(appcontent)
appcontent.addEventListener("DOMContentLoaded", loadedOverlay, true);

Detect page load completed event in Firefox

I'm writing a Firefox add-on that do something after the webpage is completely loaded.My current code is
var target = this;
const STATE_STOP = Components.interfaces.nsIWebProgressListener.STATE_STOP;
const STATE_IS_WINDOW = Components.interfaces.nsIWebProgressListener.STATE_IS_WINDOW;
const STATE_IS_DOCUMENT = Components.interfaces.nsIWebProgressListener.STATE_IS_DOCUMENT;
const locationChangeListener = {
onStatusChange: function(){},
onProgressChange: function(){},
onLocationChange: function(aWebProgress, aRequest, aLocation){},
onStateChange: function(aWebProgress, aRequest, aFlag, aStatus){
if((aFlag & STATE_STOP) && (aFlag & STATE_IS_WINDOW)){
//Do something in here
}
},
onSecurityChange: function(){}
};
gBrowser.addProgressListener(locationChangeListener);
It works fine. But sometimes, for example webpage with AJAX call, this event fired several times for one web page.
Is there any way to detect if the webpage is completely loaded or not?
If you are only interested in detecting when the page has completely loaded and not the intermediary steps it is easier to listen for load events, with something like (code from https://developer.mozilla.org/en/Code_snippets/Tabbed_browser):
function examplePageLoad(event) {
if (event.originalTarget instanceof HTMLDocument) {
var win = event.originalTarget.defaultView;
if (win.frameElement) {
// Frame within a tab was loaded. win should be the top window of
// the frameset. If you don't want do anything when frames/iframes
// are loaded in this web page, uncomment the following line:
// return;
// Find the root document:
win = win.top;
}
}
}
// do not try to add a callback until the browser window has
// been initialised. We add a callback to the tabbed browser
// when the browser's window gets loaded.
window.addEventListener("load", function () {
// Add a callback to be run every time a document loads.
// note that this includes frames/iframes within the document
gBrowser.addEventListener("load", examplePageLoad, true);
}, false);
...
// When no longer needed
gBrowser.removeEventListener("load", examplePageLoad, true);
...
gBrowser is a global var in the main firefox window (if your code is running from an overlay of browser.xul you should see it). If not (running in a sidebar for example), you can get a reference to the main window:
var mainWindow = window.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
.getInterface(Components.interfaces.nsIWebNavigation)
.QueryInterface(Components.interfaces.nsIDocShellTreeItem)
.rootTreeItem
.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
.getInterface(Components.interfaces.nsIDOMWindow);
mainWindow.gBrowser.addEventListener (...)

Categories

Resources