Capture Firefox Close Event from Extension - javascript

My extension opens up a series of additional windows. I want those windows to close when the user closes the main Firefox window. I know you can detect when a tab closes (and perhaps I should just look for the "final" tab close?) but I want to know when "all tabs" have been closed.
In short, how can I detect when the main Firefox window is closed from an extension?

You can listen the unload event.
If you script run on all type of windows, then check the url whether a browser window.
window.addEventListener('unload', function(event) {
if (event.target.location.href !== 'chrome://browser/content/browser.xul') {
return;
}
// do you stuff...
}, false);

I found one solution, although it doesn't actually listen for a particular event. Instead, we setup an interval to check if the tab container is still available.
setInterval(function() {
if (typeof gBrowser.mTabContainer === 'undefined') {
// Rest of your code...
}
}, 500);
If there's a cleaner way of doing this, I'd be more than happy to see it.

Related

how to close browser tab using js? [duplicate]

I want to create a link on a webpage that would close the currently active tab in a browser without closing other tabs in the browser. When the user clicks the close link, an alert message should appear asking the user to confirm with two buttons, "YES" and "NO". If the user clicks "YES", close that page and If "NO", do nothing.
How can it be done? Any suggestions?
You will need Javascript to do this. Use window.close():
close();
Note: the current tab is implied. This is equivalent:
window.close();
or you can specify a different window.
So:
function close_window() {
if (confirm("Close Window?")) {
close();
}
}
with HTML:
close
or:
close
You return false here to prevent the default behavior for the event. Otherwise the browser will attempt to go to that URL (which it obviously isn't).
Now the options on the window.confirm() dialog box will be OK and Cancel (not Yes and No). If you really want Yes and No you'll need to create some kind of modal Javascript dialog box.
Note: there is browser-specific differences with the above. If you opened the window with Javascript (via window.open()) then you are allowed to close the window with javascript. Firefox disallows you from closing other windows. I believe IE will ask the user for confirmation. Other browsers may vary.
Try this
close
This method works in Chrome and IE:
<a href="blablabla" onclick="setTimeout(function(){var ww = window.open(window.location, '_self'); ww.close(); }, 1000);">
If you click on this the window will be closed after 1000ms
</a>
As far as I can tell, it no longer is possible in Chrome or FireFox. It may still be possible in IE (at least pre-Edge).
Sorry for necroposting this, but I recently implemented a locally hosted site that had needed the ability to close the current browser tab and found some interesting workarounds that are not well documented anywhere I could find, so took it on myself to do so.
Note: These workarounds were done with a locally hosted site in mind, and (with the exception of Edge) require the browser to be specifically configured, so would not be ideal for publicly hosted sites.
Context:
In the past, the jQuery script window.close() was able to close the current tab without a problem on most browsers. However, most modern browsers no longer support this script, potentially for security reasons.
Current Functionality:
window.close() will work on tabs opened by a script, or by an anchor with target="_blank" (opened in a new tab)
See #killstreet's comment on #calios's answer
Browser Specific work-arounds:
Google Chrome:
Chrome does not allow the window.close() script to be to be run and nothing happens if you try to use it. By using the Chrome plugin TamperMonkey however we can use the window.close() method if you include the // #grant window.close in the UserScript header of TamperMonkey.
For example, my script (which is triggered when a button with id = 'close_page' is clicked and if 'yes' is pressed on the browser popup) looks like:
// ==UserScript==
// #name Close Tab Script
// #namespace http://tampermonkey.net/
// #version 1.0
// #description Closes current tab when triggered
// #author Mackey Johnstone
// #match http://localhost/index.php
// #grant window.close
// #require http://code.jquery.com/jquery-3.4.1.min.js
// ==/UserScript==
(function() {
'use strict';
$("#close_page").click(function() {
var confirm_result = confirm("Are you sure you want to quit?");
if (confirm_result == true) {
window.close();
}
});
})();
Note: This solution can only close the tab if it is NOT the last tab open however. So effectively, it cannot close the tab if it would cause window to closes by being the last tab open.
Firefox:
Firefox has an advanced setting that you can enable to allow scripts to close windows, effectively enabling the window.close() method. To enable this setting go to about:config then search and find the dom.allow_scripts_to_close_windows preference and switch it from false to true.
This allows you to use the window.close() method directly in your jQuery file as you would any other script.
For example, this script works perfectly with the preference set to true:
<script>
$("#close_page").click(function() {
var confirm_result = confirm("Are you sure you want to quit?");
if (confirm_result == true) {
window.close();
}
});
</script>
This works much better than the Chrome workaround as it allows the user to close the current tab even if it is the only tab open, and doesn't require a third party plugin. The one downside however is that it also enables this script to be run by different websites (not just the one you are intending it to use on) so could potentially be a security hazard, although I cant imagine closing the current tab being particularly dangerous.
Edge:
Disappointingly Edge actually performed the best out of all 3 browsers I tried, and worked with the window.close() method without requiring any configuration. When the window.close() script is run, an additional popup alerts you that the page is trying to close the current tab and asks if you want to continue.
Edit:
This was on the old version of Edge not based on chromium. I have not tested it, but imagine it will act similarly to Chrome on chromium based versions
Final Note: The solutions for both Chrome and Firefox are workarounds for something that the browsers intentionally disabled, potentially for security reasons. They also both require the user to configure their browsers up to be compatible before hand, so would likely not be viable for sites intended for public use, but are ideal for locally hosted solutions like mine.
It is possible. I searched the whole net for this, but once when i took one of microsoft's survey, I finally got the answer.
try this:
window.top.close();
this will close the current tab for you.
The following works for me in Chrome 41:
function leave() {
var myWindow = window.open("", "_self");
myWindow.document.write("");
setTimeout (function() {myWindow.close();},1000);
}
I've tried several ideas for FF including opening an actual web-page, but nothing seems to work. As far as I understand, any browser will close a tab or window with xxx.close() if it was really opened by JS, but FF, at least, cannot be duped into closing a tab by opening new content inside that tab.
That makes sense when you think about it - a user may well not want JS closing a tab or window that has useful history.
Try this as well. Working for me on all three major browsers.
<!-- saved from url=(0014)about:internet -->
<a href="#" onclick="javascript:window.close();opener.window.focus();" >Close Window</a>
window.close() doesn't work in 2k21 because Scripts may close only the windows that were opened by them.
BUT if the tab is opened in the browser not manually, but automatically - then window.close() works.
Automatically (when close() works):
<a href="/close" target="_blank"> the browser will open address in the new tab and this tab can be closed with close()
when new browser tab is opened from another application (when you click a link in Telegram/Whatsup/Outlook etc) - OS will open new tab and it can be closed with close()
when you open the with window.open('ya.ru') - for sure it can be closed with close()
Manually (when it doesn't work):
when you open fresh browser and type in the address.
when you click (+) to open new tab and type in the address
Tested successfully in FF 18 and Chrome 24:
Insert in head:
<script>
function closeWindow() {
window.open('','_parent','');
window.close();
}
</script>
HTML:
Close Window
Credits go to Marcos J. Drake.
As for the people who are still visiting this page, you are only allowed to close a tab that is opened by a script OR by using the anchor tag of HTML with target _blank. Both those can be closed using the
<script>
window.close();
</script>
<button class="closeButton" style="cursor: pointer" onclick="window.close();">Close Window</button>
this did the work for me
a bit late but this is what i found out...
window.close() will only work (IE is an exception) if the window that you are trying to close() was opened by a script using window.open() method.
!(please see the comment of #killstreet below about anchor tag with target _blank)
TLDR: chrome & firefox allow to close them.
you will get console error:
Scripts may not close windows that were not opened by script.
as an error and nothing else.
you could add a unique parameter in the URL to know if the page was opened from a script (like time) - but its just a hack and not a native functionality and will fail in some cases.
i couldn't find any way to know if the page was opened from a open() or not,
and close will not throw and errors.
this will NOT print "test":
try{
window.close();
}
catch (e){
console.log("text");
}
you can read in MDN more about the close() function
It is guaranteed that the closing of tabs will not be tolerated in any future browsers. Using scripts like mentioned above will not work.
My solution was to use a Chrome Extension. A Chrome Extension can require tab manipulation permissions so it will be easy to handle the closing of any tab from the domain in which the extension's content script is active.
This is how the background script should look like:
chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) {
console.log(sender)
console.log(message)
if(message.closeThis) {
closeTab(sender.tab.id)
}
});
const closeTab = id => {
console.log("Closing tab");
chrome.tabs.remove(id);
}
The content script should look like this:
window.addEventListener("message", (event) => {
// Only accept messages from ourselves
if (event.source !== window)
return;
if (event.data.type && (event.data.type === "APPLICATION/CLOSE")) {
console.log("Content script received APPLICATION/CLOSE event");
chrome.runtime.sendMessage({closeThis: true});
}
}, false);
Close the tab by calling this in your application (make sure the content scripts are enabled in your domain by specifying that in the manifest):
window.postMessage({ type: "APPLICATION/CLOSE" }, "*");
Be cautious when using this because Chrome Extensions' deployment can be a pain.
I just wanted to add that window.close() works in 2021, chrome 91, but not always. One of the cases when it works if there is no history in tab (you can't go back).
In my case I wanted to create self-destructing tab which closes after few seconds, but I was struggling with how to go to development server avoiding new tab, because apparently New tab is also tab and it is being saved in tab history :D I created link in about:blank tab with target=_blank attribute and it was leading to new tab where window.close() method finally worked!
This is one way of solving the same, declare a JavaScript function like this
<script>
function Exit() {
var x=confirm('Are You sure want to exit:');
if(x) window.close();
}
</script>
Add the following line to the HTML to call the function using a <button>
<button name='closeIt' onClick="Exit()" >Click to exit </Button>
You can try this solution to trick the browser to close the current window using JavaScript + HTML:
JS:
function closeWindow() {
if(window.confirm('Are you sure?')) {
window.alert('Closing window')
window.open('', '_self')
window.close()
}
else {
alert('Cancelled!')
}
}
HTML:
Some content
<button onclick='closeWindow()'>Close Current Window!</button>
More content
Due to strict browser behaviors, window.close() will only work if it's opened by window.open(...)
But I made a solution for this!
Add an empty hashtag with window.open(...) when it is NOT included
When the perfect time for closing occurs, call window.close
If 2. has returned an error, replace any hashtag or HTTP parameters with an empty hashtag and finally close the window
<button onclick="myFunction()">Close</button>
<script>
if (location.href.indexOf("#") == -1) {
window.open(location.href + "#", "_self")
}
function myFunction() {
try {
window.close()
} catch (err) {
window.open(location.href.substring(0, location.href.indexOf("?")).substring(0, location.href.indexOf("#")) + "#", "_self")
window.close()
}
}
</script>
Type close in this live demo
Here's how you would create such a link:
close

How to save fullscreen state in Firefox?

Following Mozilla's API document on Fullscreen, I've placed the following code in my website, it simply takes the whole document (html element) and makes the page go fullscreen once the user clicks anywhere in the page, and once there's another click, page goes back to normal.
var videoElement = document.getElementsByTagName('html')[0];
function toggleFullScreen() {
if (!document.mozFullScreen) {
if (videoElement.mozRequestFullScreen) {
videoElement.mozRequestFullScreen();
}
} else {
if (document.mozCancelFullScreen) {
document.mozCancelFullScreen();
}
}
}
window.addEventListener("click", function(e) {
toggleFullScreen();
}, false);
My question is how can I save this fullscreen state so every time that Firefox loads up, that page is still on fullscreen.
Or any workaround? This is for Firefox for Android.
It's an extreme workaround, but you can make your website a progressive web app and put "display": "fullscreen" in its manifest. Then you can launch your site from the home screen and use it like a fullscreen native app.
Following my experiments and the specs, this isn't doable, from client browser javascript
This api need an user interaction. We can't activate the fullscreen by scripting.
From the fullscreen api specification:
Fullscreen is supported if there is no previously-established user
preference, security risk, or platform limitation.
An algorithm is allowed to request fullscreen if one of the following
is true:
The algorithm is triggered by user activation.
The algorithm is triggered by a user generated orientation change.
https://fullscreen.spec.whatwg.org/#model
About activation events:
An algorithm is triggered by user activation if any of the following
conditions is true:
The task in which the algorithm is running is currently processing an
activation behavior whose click event's isTrusted attribute is true.
The task in which the algorithm is running is currently running the
event listener for an event whose isTrusted attribute is true and
whose type is one of:
change
click
dblclick
mouseup
pointerup
reset
submit
touchend
https://html.spec.whatwg.org/multipage/interaction.html#triggered-by-user-activation
We can't trigger fullscreens from scripts, or if so, the script must be triggered by the user.
Including simulating a click won't works, this is regular behavior, made to protect user experience.
With some reflexion, we can't agree more on this, imagine any ads page can launch full screens, the web would be a hell to browse!
You told in comment: «I am the only user here»
What you can do if using unix: (( probably alternatives exists in other os )).
Using midori (a lightweight webkit browser), this will start a real fullscreen.
midori -e Fullscreen -a myurl.html
There is no ways to start firefox or chromium in a fullscreen state from the command line, to my knowledge.
But what is doable is to trigger a F11 click at system level, focusing on the good window, just after the page launch. ((sendkey in android adb shell?))
xdotool can do that.
Here is a pipe command line that will launch firefox with myurl.html, search for the most recent firefox window id, then trigger the F11 key on this window.. (Press F11 again to exit)
firefox myurl.html && xdotool search --name firefox | tail -1 | xdotool key F11
This should be easy to adapt for other browsers.
As last alternative, have a look at electron or nw.js.
take a look at this add on for Firefox, i have not tried it, as I'm posting this from mobile, it's description does say that it can force start in full screen. I'm just quoting their description .
Saves the last state or force start in full screen forever! Simple and
complete for this purpose.
Edit : And the link to it
https://addons.mozilla.org/en-US/firefox/addon/mfull/
What about using localStorage like this?
function goFullScreen() {
if (videoElement.mozRequestFullScreen) {
localStorage.setItem('fullscreenEnabled', true)
videoElement.mozRequestFullScreen();
}
}
window.onload = function () {
if (localStorage.getItem('fullscreenEnabled') === true) {
goFullScreen();
}
};
function toggleFullScreen() {
if (!document.mozFullScreen) {
goFullScreen();
} else {
if (document.mozCancelFullScreen) {
document.mozCancelFullScreen();
localStorage.setItem('fullscreenEnabled', false)
}
}
}
window.addEventListener("click", function(e) {
toggleFullScreen();
}, false)

What's the event for leaving the IE tab?

I want my javascript to be trigged when:
The current IE tab is switched out when multiple IE tabs are open.
When the current IE tab is closed.
I don't want my JS code be trigged by the in-page pops up dialogs.
When the whole IE window closed.
The lose focus event may not work for me because there are pop up diaglogs in my page, so when it pops out, the IE tab will lose focus, but since the tab is not switched or closed, I don't want my javascript to be trigged here.
Is there any solution? I am wondering if there's something like entering tab / leaving tab, or tab-switching events?
Some interesting links, but not resolve my question.
Is there a way to detect if a browser window is not currently active?
Hook into tab changed event of browser
if you use 'jQuery', you can easily do it .
$(window).blur(function(){
// your code
});
$(window).focus(function(){
// your code
});
here is the link which provides one more method to do it.
you may be interested in
(function(){
function doOnFocus(){ console.log("focus"); }
function doOnBlur(){ console.log("blur"); }
function doOnLeave(){ console.log("leave"); }
if('onfocusout' in document){
document.onfocusout = doOnBlur;
document.onfocusin = doOnFocus;
}else{
window.onblur = doOnBlur;
window.onfocus = doOnFocus;
}
window.onbeforeunload = doOnLeave;
})();
In javascript there is an event on window close it is not IE specific but is mostly used to call an alert before the user leaves the page. It's one of my pet peeves and is very annoying but may be what you are looking for.
window.onbeforeunload = yourfunctionthatexecutes;

Is there an event for when a Chrome Extension popup is closed?

I've already tried window.unload, window.beforeunload, etc.
I'm looking for a way to notify my background page once the popup is closed.
You can try this. Connect to your background page with chrome.runtime.connect (or chrome.extension.connect before Chrome 26) and port.onDisconnect will be fired in your background page when the popup is closed.
It's as simple as that:
// popup.js
chrome.runtime.connect({ name: "popup" });
// background.js
chrome.runtime.onConnect.addListener(function(port) {
if (port.name === "popup") {
port.onDisconnect.addListener(function() {
console.log("popup has been closed")
});
}
});
Note that there are some edge cases where this method doesn't work. E.g. when having the popup open and then switching tabs by using a keyboard shortcut such as ctrl + t for example.
Probably a hacky way, but in the popup page you can listen to
window.onblur = function(){}
and send a message to active tab.
There is currently no way to figure out when the browser action popup was
closed as window.unonload is triggered immediately when the popup finished
loading, not when it's closed. There is a bug crbug.com/31262 for this.
Three work arounds available are well described here. They include the port.onDisconnect trick and periodically polling chrome.extension.getViews() from either the popup or a background page.
I'm surprised noone mentioned this (I've tested it on Firefox Nightly and it works there):
window.addEventListener("pagehide", function(event) {
console.log(event);
});
This is the solution I used for manifest V3:
Set up a connection in your popup's JavaScript file
chrome.runtime.connect();
In background.js, use onConnect to listen for the event
chrome.runtime.onConnect.addListener(port => {
port.onDisconnect.addListener(()=>{
//Your event will be fired in here
})
})
Finally found the solution. Put below code in background.js/eventPage.js:
chrome.windows.onFocusChanged.addListener(function(window) {
//handle close event
});
Try to use the visibilitychange event on the document object. It works fine for me:
document.addEventListener('visibilitychange', MyFunction, false);

In JavaScript, what is event.isTrigger?

I came across this in some JS code I was working on:
if ( typeof( e.isTrigger ) == 'undefined' ) {
// do some stuff
}
This seems to be part of jQuery. As far as I can see it tells you if an event originated with the user or automatically.
Is this right? And given that it's not documented, is there a way of finding such things out without going behind the curtain of the jQuery API?
In jQuery 1.7.2 (unminified) line 3148 contains event.isTrigger = true; nested within the trigger function. So yes, you are correct - this is only flagged when you use .trigger() and is used internally to determine how to handle events.
If you look at jQuery github project, inside trigger.js file line 49 (link here) you can find how isTrigger gets calculated.
If you add a trigger in your JavaScript and debug through, You can see how the breakpoint reaches this codeline (checked in jQuery-2.1.3.js for this SO question)
Modern browsers fight against popup windows opened by automated scripts, not real users clicks. If you don't mind promptly opening and closing a window for a real user click and showing a blocked popup window warning for an automated click then you may use this way:
button.onclick = (ev) => {
// Window will be shortly shown and closed for a real user click.
// For automated clicks a blocked popup warning will be shown.
const w = window.open();
if (w) {
w.close();
console.log('Real user clicked the button.');
return;
}
console.log('Automated click detected.');
};

Categories