I'm trying to figure out how to make a play/pause functionality for my chrome extension. I've figured it out and it works however, for usability I now am trying to get the popup window to:
Keep the checkbox checked if it was before closing the popup.
Keep the content that popup.js wrote into a span tag before closing the popup.
My popup.html is:
<script src="popup.js"></script>
<div class="container">
<div class="checkbox">
<p>Check the box to pause the extension</p>
<input type="checkbox" id="switcher" name="switcher">
<p><span id="extensionStatus"></span></p>
</div>
<a id="submit" href="#">Save</a>
</div>
And my popup.js is:
document.addEventListener('DOMContentLoaded', function() {
var link = document.getElementById('submit');
link.addEventListener('click', function() {
var status;
var switcher = document.getElementById('switcher');
var updateStatus = document.getElementById("extensionStatus");
if(switcher.checked == true) {
status = "paused";
} else {
status = "play";
}
chrome.storage.sync.set({'status': status});
chrome.storage.sync.get('status', function (result) {
status = result.status;
updateStatus.innerHTML = "Current Status: " + status;
if(status == "paused") {
switcher.checked = true;
}
});
});
});
I set have to set the value in storage as I also use the value to do other code on content-script file.
Basically where the line that writes the innerHTML and then the line that sets the checkbox to checked run fine when the popup is open and then as soon as you close the popup and reopen obviously the session resets.
I know it needs something like this in the popup.js instead but I am not quite sure what to put in the function in the background.js as I can't/don't know how to access the popup DOM from background.js:
var backgroundPage = chrome.runtime.getBackgroundPage();
backgroundPage.savePopup();
I don't know how extension storage works but here's a demo which works with local storage. Maybe it can help you with the extension.
Demo
document.addEventListener('DOMContentLoaded', function() {
if (localStorage.getItem('status') == 'paused') {
switcher.checked = true;
}
var link = document.getElementById('submit');
link.addEventListener('click', function() {
var status;
var switcher = document.getElementById('switcher');
var updateStatus = document.getElementById("extensionStatus");
console.log('staus:', localStorage.getItem('status'));
if (switcher.checked == true) {
status = "paused";
} else {
status = "play";
}
localStorage.setItem('status', status);
});
});
I have tried many methods to detect browser close event through jQuery or JavaScript. But, unfortunately, I have not been able to detect the close. The onbeforeunload and onunload methods are also not working.
How do I detect the window close, unload, or beforeunload events?
Have you tried this code?
window.onbeforeunload = function (event) {
var message = 'Important: Please click on \'Save\' button to leave this page.';
if (typeof event == 'undefined') {
event = window.event;
}
if (event) {
event.returnValue = message;
}
return message;
};
$(function () {
$("a").not('#lnkLogOut').click(function () {
window.onbeforeunload = null;
});
$(".btn").click(function () {
window.onbeforeunload = null;
});
});
The second function is optional to avoid prompting while clicking on #lnkLogOut and .btn elements.
One more thing, The custom Prompt will not work in Firefox (even in latest version also). For more details about it, please go to this thread.
Referring to various articles and doing some trial and error testing, finally I developed this idea which works perfectly for me.
The idea was to detect the unload event that is triggered by closing the browser. In that case, the mouse will be out of the window, pointing out at the close button ('X').
$(window).on('mouseover', (function () {
window.onbeforeunload = null;
}));
$(window).on('mouseout', (function () {
window.onbeforeunload = ConfirmLeave;
}));
function ConfirmLeave() {
return "";
}
var prevKey="";
$(document).keydown(function (e) {
if (e.key=="F5") {
window.onbeforeunload = ConfirmLeave;
}
else if (e.key.toUpperCase() == "W" && prevKey == "CONTROL") {
window.onbeforeunload = ConfirmLeave;
}
else if (e.key.toUpperCase() == "R" && prevKey == "CONTROL") {
window.onbeforeunload = ConfirmLeave;
}
else if (e.key.toUpperCase() == "F4" && (prevKey == "ALT" || prevKey == "CONTROL")) {
window.onbeforeunload = ConfirmLeave;
}
prevKey = e.key.toUpperCase();
});
The ConfirmLeave function will give the pop up default message, in case there is any need to customize the message, then return the text to be displayed instead of an empty string in function ConfirmLeave().
Try following code works for me under Linux chrome environment. Before running make sure jquery is attached to the document.
$(document).ready(function()
{
$(window).bind("beforeunload", function() {
return confirm("Do you really want to close?");
});
});
For simple follow following steps:
open http://jsfiddle.net/
enter something into html, css or javascript box
try to close tab in chrome
It should show following picture:
Hi i got a tricky solution, which works only on new browsers:
just open a websocket to your server, when the user closes the window, the onclose event will be fired
Following script will give message on Chrome and IE:
<script>
window.onbeforeunload = function (e) {
// Your logic to prepare for 'Stay on this Page' goes here
return "Please click 'Stay on this Page' and we will give you candy";
};
</script>
Chrome
IE
on Firefox you will get generic message
Mechanism is synchronous so no server calls to delay will work, you still can prepare a mechanism like modal window that is shown if user decides to stay on page, but no way to prevent him from leaving.
Response to question in comment
F5 will fire event again, so will Atl+F4.
As Phoenix said, use jQuery .bind method, but for more browser compatibility you should return a String,
$(document).ready(function()
{
$(window).bind("beforeunload", function() {
return "Do you really want to close?";
});
});
more details can be found at : developer.mozilla.org
jQuery .bind() has been deprecated. Use .on() instead
$(window).on("beforeunload", function() {
runBeforeClose();
});
Maybe it's better to use the path detecting mouse.
In BrowserClosureNotice you have a demo example and pure javascript library to do it.
It isn't perfect, but avoid problems of document or mouse events...
<script type="text/javascript">
window.addEventListener("beforeunload", function (e) {
var confirmationMessage = "Are you sure you want to leave this page without placing the order ?";
(e || window.event).returnValue = confirmationMessage;
return confirmationMessage;
});
</script>
Please try this code, this is working fine for me. This custom message is coming into Chrome browser but in Mozilla this message is not showing.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script type="text/javascript" language="javascript">
var validNavigation = false;
function endSession() {
// Browser or broswer tab is closed
// Do sth here ...
alert("bye");
}
function wireUpEvents() {
/*
* For a list of events that triggers onbeforeunload on IE
* check http://msdn.microsoft.com/en-us/library/ms536907(VS.85).aspx
*/
window.onbeforeunload = function() {
if (!validNavigation) {
var ref="load";
$.ajax({
type: 'get',
async: false,
url: 'logout.php',
data:
{
ref:ref
},
success:function(data)
{
console.log(data);
}
});
endSession();
}
}
// Attach the event keypress to exclude the F5 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;
});
}
// Wire up the events as soon as the DOM tree is ready
$(document).ready(function() {
wireUpEvents();
});
</script>
This is used for when logged in user close the browser or browser tab it will automatically logout the user account...
You can try something like this.
<html>
<head>
<title>test</title>
<script>
function openChecking(){
// alert("open");
var width = Number(screen.width-(screen.width*0.25));
var height = Number(screen.height-(screen.height*0.25));
var leftscr = Number((screen.width/2)-(width/2)); // center the window
var topscr = Number((screen.height/2)-(height/2));
var url = "";
var title = 'popup';
var properties = 'width='+width+', height='+height+', top='+topscr+', left='+leftscr;
var popup = window.open(url, title, properties);
var crono = window.setInterval(function() {
if (popup.closed !== false) { // !== opera compatibility reasons
window.clearInterval(crono);
checkClosed();
}
}, 250); //we check if the window is closed every 1/4 second
}
function checkClosed(){
alert("closed!!");
// do something
}
</script>
</head>
<body>
<button onclick="openChecking()">Click Me</button>
</body>
</html>
When the user closes the window, the callback will be fired.
I've come across a nasty website that managed to refresh the page every time I tried to close the tab. Basically you couldn't close that page. I got around it by disabling javascript on that page.
How do they do it?
I've tried location.replace inside onbeforeunload and it doesn't work:
window.onbeforeunload = function(e) {
window.location.replace(window.location.href);
};
Here is the source of the page in question, where I don't get how they do it:
<script type="text/javascript">
function c(b)
{
document.write(b);
}
function wrapped3(d)
{
return d.replace(/(.)(.)/g, '%$1$2');
}
function wrapped(b)
{
var tmp = window['decodeURI' + 'Component'];
return tmp(wrapped3(b))
}
function show_page(a)
{
c(wrapped(a)
.split('{{addr}}').join('//ip')
.split('{{country}}').join('Great Britain')
.split('{{region}}').join('London, City of')
.split('{{city}}').join('London')
.split('{{ltude}}').join('//latitude')
.split('{{referrer}}').join('//url here')
);
}
show_page('//long string here');
</script>
window.onbeforeunload is the correct solution, here is an example:
var popit = true;
window.onbeforeunload = function() {
if(popit == true) {
popit = false;
return "Are you sure you want to leave?";
}
}
http://jsfiddle.net/SQAmG/3/
I'm trying to use a simple string stored in the localStorage functionality built into phonegap as a simple setting to deicide witch set of data to fetch from a server. In the index.html I've been able to save a string from a <select> menu and display it in the header. Using this javascript code:
<script type="text/javascript" charset="utf-8">
window.onload = function() {
document.getElementById("BtnStore").addEventListener("click", storeData, false);
$("#headertitle").append(loadData()).headertitle("refresh");
}
function storeData() {
var e = document.getElementById("klass");
var klass = e.options[e.selectedIndex].value;
localStorage.setItem("klass", klass);
window.location.href = "index.html";
}
function loadData() {
var getKlass = localStorage.getItem("klass");
return getKlass;
}
</script>
This appends the stored value in an <h1> element.
But when I from a different html page try to reference the same key from the localstore, nothing is being displayed. Here is that code:
<script type="text/javascript" charset="utf-8">
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
$("#hejsan").append(loadData()).hejsan("refresh");
};
function loadData() {
var getKlass = localStorage.getItem("klass");
return getKlass;
}
</script>
This is also just as a test, appending the string to a <p> element. For some reason nothing is happening, someone knows why?
Thanks
I figured out how to make it work, here is the code i used:
First page:
<script type="text/javascript" charset="utf-8">
window.onload = function() {
document.getElementById("BtnStore").addEventListener("click", storeData, false);
$("#headertitle").html(loadData()).headertitle;
}
function storeData() {
//localStorage.clear();
var e = document.getElementById("klass");
var klass = e.options[e.selectedIndex].value;
localStorage.setItem("klass", klass);
window.location.href = "index.html";
}
function loadData() {
var getKlass = localStorage.getItem("klass");
return getKlass;
}
</script>
Second page:
$(document).ready(function() {
function loadData() {
var getKlass = localStorage.getItem("klass");
$("#hejsan").html(getKlass).hejsan;
}
loadData();
}
If anyone else gets stuck! :)
I am working on asp.net(c#).I try to add a javascript alert when a user tries to close the current tab in browser. The code is not working in Chrome.Please can any one help about this topic.
This is my code:
<script type="text/javascript">
window.onbeforeunload = function close_window() {
var r = confirm("Do you want to view other topics?");
if (r == true)
{
alert("You pressed OK!");
var Url = "http://stackoverflow.com/";
window.location = Url;
return false;
}
else
{
window.close();
}
}
Remove the () when you're calling the function.
It should be:
window.onbeforeunload = function close_window {
Actually, try this.
function close_window() {
...
}
window.onbeforeunload = close_window;
And yes--it's really bad practice.