Detect when a user leaves a page and write a cookie - javascript

I am implementing a cookie banner and need to have inferred consent once the user has seen the banner. I am therefore trying to write a cookie once the user starts to navigate the site to say they've seen the cookie banner. I've tried using beforeunload and unload, but neither seem to do anything.
The latest bit of code I've used this is:
<script>
$(window).unload(function () {
jQuery.post("/set-cookie-preference", { cookiePreference: 3 },
function (data) {
//document.location.reload();
});
});
</script>
I also tried:
<script type="text/javascript">
function closeIt() {
jQuery.post("/set-cookie-preference", { cookiePreference: 3 },
function (data) {
//document.location.reload();
});
}
window.onbeforeunload = closeIt;
</script>
But neither seem to work. Any ideas?

You could use LocalStorage. It works the same like a cookie, but it has some more benefits, in my opinion. A LocaStorage object can only be removed by the user (like when we wipes his browser history). To set a normal PHP cookie you have to set a time.
You can read more about it here:
http://www.w3schools.com/html/html5_webstorage.asp
All major browsers (Chrome, IE, FireFox, Safari) support LocalStorage. Even IE 8 supports LocalStorage!

Related

jquery cookie , still set after clear browser history

I'm using a simple script to show a popup with a checkbox to not show it again, and it works just fine, and it works perfectly to delete the cookie via the script.
My problem is that if i delete the cookies in IE11 (company browser), the cookie is still set!
So what am i missing? Is the cookie stored somewhere other than the standard directory when using jquery.cookie.js ?
I want to be able to see the popup by delete the cookie locally.
My code for reference:
<script type="text/javascript">
$("#Cookiehandler").change(function() {
if(this.checked) {
$.cookie('the_cookie', 'no');
}
});
window.jQuery(document).ready(function() {
if($.cookie('the_cookie') == null) {
$.fancybox.open('#popup_box');
}
else {
// placeholder
}
});
//$.removeCookie("the_cookie");
//alert( $.cookie("the_cookie") );
</script>
Best regards,
Marcus
I think the best way might be for you to have an administrative page with a script that deletes the cookie and just to visit that page whenever you want the cookie to be killed. That's a browser-independent method and you don't have to worry about where the cookie was stored, nor do you have to worry about doing it from a bunch of different browsers manually. Just visit the admin page from some or all of your browsers and it's done...for those browsers...while leaving the other ones alone unless you browse the kill page from them too.

JavaScript - bfcache/pageshow event - event.persisted always set to false?

In a standard Java / SpringMVC / JSP / jQuery web-app, I'm trying to detect a "Back" (or history.go(-1)) event, in order to refresh (AJAX) a summary component/panel content when I return to a page (where we can change the backend data that is displayed by the summary component).
I tried the following in JavaScript (following some posts on StackExchange re how to achieve this):
<script type="text/javascript">
$(document).ready(function() {
window.onpageshow = function(event) {
console.log("Event:");
console.dir(event);
if (event.persisted) {
alert("non-jQuery - back to page - loaded from bfcache");
} else {
alert("non-jQuery - loaded page from server");
}
};
$(window).on("pageshow", function(event){
console.log("Event:");
console.dir(event);
if (event.originalEvent.persisted) {
alert("jquery - back to page - loaded from bfcache");
} else {
alert("jquery - loaded page from server");
}
});
});
</script>
I am running OpenSUSE Linux and have tried this with FireFox and Chrome (latest versions), but every time the event's persisted attribute is set to false (I can see this in the JavaScript console and by the alerts that pop-up from the above code). By every time, I mean, regardless of whether it was loaded from the server or shown again via the Back button (or a 'Back' link).
My intention was to make an AJAX call to reload the summary component/panel with the updated data from the server if the page was showing via the Back button or history.go(-1) call.
I also tried setting an unload handler (that does nothing) to prevent the page from being put into the bfcache but it still seems to be showing a bf-cached version and the event.persisted (or event.originalEvent.persisted) is set to false.
Is this property managed correctly on Linux? Am I doing something stupid in my code? Any help or ideas would be much appreciated, thanks!
I have found hidden input buttons are not a reliable solution since they may hold the wrong value when the user navigates back to the page and then hits refresh. Some browsers (Firefox) retain input values on refresh so every time the user hits refresh it will refresh again since the input button holds the wrong value. This is a typical scenario for forums (user views a topic, hits the back button to go back to the list of topics, and may continue to hit refresh to check if there are new topics).
As noted by Grégoire Clermont, event.persisted is buggy in chrome (and IE) and this still hasn't been fixed for either browser as of Feb 2017. The good news is you can rely on window.performance.navigation.type == 2 for chrome and IE. Ironically Firefox is unreliable for the latter but it shouldn't matter since it is reliable for event.persisted. The following code worked for me:
if (document.addEventListener) {
window.addEventListener('pageshow', function (event) {
if (event.persisted || window.performance &&
window.performance.navigation.type == 2)
{
location.reload();
}
},
false);
}
Update 2022:
Because window.performance.navigation.type is deprecated (ref: MDN), I updated the code to do the same thing:
if (document.addEventListener) {
window.addEventListener('pageshow', function (event) {
if (event.persisted || performance.getEntriesByType("navigation")[0].type === 'back_forward') {
location.reload();
}
},
false);
}
This appears to be a bug in Chrome (also present in IE11).
I have found the following workaround:
<input type="hidden" id="cacheTest"></input>
<script>
var input = document.querySelector('#cacheTest')
if (input.value === "") {
// the page has been loaded from the server,
// equivalent of persisted == false
}
else {
// the page has been loaded from the cache,
// equivalent of persisted == true
}
// change the input value so that we can detect
// if the page is reloaded from cache later
input.value = "some value"
</script>
This exploits the fact that in most browsers, when the page is loaded from the cache, form fields values are also conserved.
I know this is a bit late but this works for me:
window.onpageshow = function(e) {
if (e.persisted) {
alert("Page shown");
window.location.reload();
}
};
I don't think you need it in the document ready function, just use vanilla as above.

Chrome not supporting my javascript

I just want, when a user comes to my site and closes the window, then I want to know the reason for leaving from my site.
So I'm sending the user to a survey page, using the following script.
It works in every browser but not in Chrome
<script type="text/javascript">
window.onbeforeunload = confirmExit;
function confirmExit() {
if (location.href.indexOf("index.php") != -1)
{
location.href = "http://www.test.com/survey.php";
return "Press 'cancel to go 'survey'";
}
}
</script>
Have you tried to use window.location = ("http://www.test.com/survey.php"); or window.open ("http://www.test.com/survey.php"); instead? That may be easier to do.
You can also do window.open ("http://www.test.com/survey.php", '_newtab'); This will make users less upset off when they are forced to redirect after leaving, because it will be in a new tab.
Well, sometimes there is a good reason for such a code user310850 is quoting
not all websites are in Web, some of them are internal corporate websites
Some if not most of big companies still use IE 6 as standard browser
I would use unload event handler. I assume jquery is good
$(window).unload(function() {
//your code here
});

How can I launch the eMail client, and then do a page redirect with Javascript?

I'm required to make a website function exactly the same on other browsers as it does in IE6. Part of the current code looks similar to this:
<script>
function myFunc(){
location.href="mailto:test#test.com&body=Hello!";
location.href="newPage.html";
}
</script>
<body onload="myFunc();">
</body>
in IE, this causes the mail client to open with the specified message prepared, and then redirects the browser to newPage.html. Other browsers, however, only redirect to newPage.html. How can I achieve this effect (opening the mail client and then doing a page redirect) consistently across browsers?
As a note, I've also tried to accomplish this using meta refresh, but was unsuccessful.
Try using something like:
send
Instead of at the onload.
Changing the href property will start a location load, changing it again afterwards will cancel the previous navigation.
It appears that IE6 will start the e-mail client immediately upon setting the property, then continue the javascript execution. Other browsers appear to do things differently, and the second location load will cancel the first.
I managed to work around this in Chrome with a timer, it might work for other browsers too:
function myFunc(){
location.href="mailto:test#test.com&body=Hello!";
window.setTimeout(function () { location.href="newPage.html" }, 0);
}
On the whole, I tend to think security settings will get in your way and would recommend just giving the user a boring old-fashioned mailto link to click. (Edit: Perhaps one set up like Mic suggests.)
That said, I wonder if things become any more reliable if you introduce a delay:
function myFunc() {
location.href = "mailto:test#test.com&body=Hello!";
setTimeout(function() {
location.href = "newPage.html";
}, 500);
}
This will work only if the client's browser knows which E-Mail client to open for mailto: links in the first place. If the user uses a web-based client that is not registered with the browser, nothing will happen.
Also, it could be that security settings prevent mailto: links from opening programmatically, or will prevent it in the future.
I wouldn't rely on this to work either way, only as a nice optional convenience function.
Anyway, to answer your question, can you try setting a timeout between the two calls? Maybe the location refresh is just too quick for the browser to catch up.
location.href="mailto:test#test.com&body=Hello!";
setTimeout(function(){ location.href = 'newPage.html' }, 500);
function redirect() {
setTimeout(function() {
location.href = "index.html";
}, 1000);
}

Is there a way to request permission in IE to use window.external.AddFavorite?

The JavaScript security settings on Internet Explorer for my customers disallow using window.external.AddFavorite, and it generates (best case) an error in the status bar when the users click the "Add Bookmark" link on my website. Is there a way to explicitly request permission to use the window.external.AddFavorite method from the user in Internet Explorer, when the security settings don't allow use of the rest of the window.external methods?
EDIT
Here's the code I'm working with:
<script type="text/javascript">
function addToFavorites() {
if (window.sidebar) { // Mozilla uses sidebar
window.sidebar.addPanel( document.title, window.location , "");
} else if (window.external) { // IE uses window.external
window.external.AddFavorite( window.location, document.title );
} else { // Who knows ? Only have to support IE & Moz anyhow.
alert("Sorry! Your browser doesn't support this function.");
}
}
</script>
Bookmark This Page
It will work, but it HAS to be triggered by a user driven event. (e.g. the onclick of a link/button)
This is to stop spam/adware/pr0n sites from auto stuffing your bookmarks with garbage.
I'd just pull the "Add Bookmark" link off the site. Users know how to do that if they really want to.

Categories