I'm quite new to javascript. I have a simple onbeforeunload function, which currently works for all the pages and I want it to activate for certain subpages (#clients, #products, #news) , but not for the first subpage of my domain (index.html). I'd like to avoid putting the script in each subpage, but rather would like to use conditional statement(s) to detect name of the subpage before the onbeforeunload function triggers. My current code below:
window.onbeforeunload = function(event) {
event.returnValue = "You have unsaved work";
};
I understand that I need to use window.location.href in some way, but haven't figured out yet. I tried to use the code below to get url or each site and then wanted to enter it into a case statement, the url is returned but the code from case doesn't work:
document.getElementById("demo").innerHTML =
"Page location is " + window.location.href;
Case code:
<script>
var text;
switch (window.location.href) {
case "http://mydomain/#/clients":
text = 1;
break;
case "http://mydomain/#/products/":
text = 2;
break;
case "http://mydomain/#/news":
text = 3;
break;
default
text = 4;
break;
}
document.getElementById("demo").innerHTML = "Number is " + text;
</script>
Thank you
"window.location.href" returns the entire URL, use location.pathname instead. Also, make sure to add the path names (including extension) to the pathsToAddTheScript Array.
Try this.
var pathsToAddTheScript = ['clients', 'products'];
if(window.location.pathname in pathsToAddTheScript) {
window.onbeforeunload = function(event) {
event.returnValue = "You have unsaved work";
};
}
Related
I have an html file. I don't want to open that file too many times in one browser. if in the browser I already have that html file open. then when opening another tab with the same htm file, an error will appear. Is there any way to do that?. we can use javascript, html, jquery or any other way.
The only reliable way I can see to do this is to listen to a message asking "Am I here?" on a BroadcastChannel and respond with "I am here.". At page load, ask "Am I here?" and if you get the positive response, you'll know another tab already has your page.
const bc = new BroadcastChannel("Tin huynh's Broadcast Channel");
const question = "Am I here?"
const answer = "I am here."
bc.onmessage = evt => {
if (evt.data === question) {
bc.postMessage(answer)
} else if (evt.data === answer) {
alert("I am already here.")
}
}
bc.postMessage(question)
You can use JavaScript to check if the HTML file is already open in the browser before opening it in a new tab.
function openHTMLFile() {
var isFileOpen = false;
for (var i = 0; i < window.length; i++) {
if (window[i].location.href == "https://yoursite/path/to/file.html") {
isFileOpen = true;
break;
}
}
if (!isFileOpen) {
window.open("https://yoursite/path/to/file.html", "_blank");
}
}
I have a website with tabs, where each tab is in fact in the same table with an atribute that show it or not. Then a javascript function would change the attribute when you press on the tab.
The function is something like this:
function showHide(ID) {
switch (ID) {
case 'main':
document.getElementById('main').style.display = 'block';
document.getElementById('abstracts').style.display = 'none';
break;
case 'abstracts':
document.getElementById('main').style.display = 'none';
document.getElementById('abstracts').style.display = 'block';
break;
}
return true;
}
Then, the title of the tab is something like
Main
and the tab is
<tr id="main"> ... </tr>
The thing is that I would like to be able to have a URL for a tab, for example http://mypage.com#main or something like that, so when I enter to that URL, the tab main is focussed.
Is that possible?
At the bottom of your page or window.onload, read the hash and call your method.
(function(){
var hash = window.location.hash.substr(1);
showHide(hash);
}());
and if you want the url to change, you probably want to remove the return false.
You can use hashchange event listener here.
eg :window.addEventListener("hashchange", doThisWhenTheHashChanges, false);
I'm facing problem in redirecting to html page. My scenario is :
I have two pages named First.html & Second.html. Second.html contains a link to go back i.e previous page. i have define <b>href=""</b> attribute of that link. And i call a JavaScript function goBack() on it's onClick() event. And in that I written code to redirect using <b>window.location.href</b>. Bcoz, I want to do something like below :
1. When request came from First.html, i have to go back to First.html from Second.html
2. When request came from Second.html, i have to go to same page, i.e., Second.html. Second.html's div's contents are changes dynamically using JavaScript, but the page is same.
I have tried following options :
window.location.href
document.location.href
location.href
window.url
window.location.replace(url)
location.assign(url);
Any help would be greatly appreciated.
Thanks
i got solution by myself.
In first.html
<a href="Second.html?p=First">
In Second.html
Back
<script>
var p = window.location.href;
var pre = p.substring(p.lastIndexOf('?') + 3, p.length);
var same = "";
//It changes the contents of Second.html' div tag
someFunction()
</script>
In js file
There is an event on button which come by calling someFunction(), in that
$(document).on('click', '.button1', function() {
// some extra code
same = "Second";
}
var diff;
function goBack() {
if (same == "First") {
diff = pre;
pre = same;
}
if (pre == same) {
location.href = "Second.html?p=" + diff;
same = "";
} else if (pre != 'Second') {
location.assign("" + pre + ".html");
diff = pre;
} else {
location.assign("" + diff + ".html");
}
return false;
}
Rewriting the question -
I am trying to make a page on which if user leave the page (either to other link/website or closing window/tab) I want to show the onbeforeunload handeler saying we have a great offer for you? and if user choose to leave the page it should do the normal propogation but if he choose to stay on the page I need him to redirect it to offer page redirection is important, no compromise. For testing lets redirect to google.com
I made a program as follows -
var stayonthis = true;
var a;
function load() {
window.onbeforeunload = function(e) {
if(stayonthis){
a = setTimeout('window.location.href="http://google.com";',100);
stayonthis = false;
return "Do you really want to leave now?";
}
else {
clearTimeout(a);
}
};
window.onunload = function(e) {
clearTimeout(a);
};
}
window.onload = load;
but the problem is that if he click on the link to yahoo.com and choose to leave the page he is not going to yahoo but to google instead :(
Help Me !! Thanks in Advance
here is the fiddle code
here how you can test because onbeforeunload does not work on iframe well
This solution works in all cases, using back browser button, setting new url in address bar or use links.
What i have found is that triggering onbeforeunload handler doesn't show the dialog attached to onbeforeunload handler.
In this case (when triggering is needed), use a confirm box to show the user message. This workaround is tested in chrome/firefox and IE (7 to 10)
http://jsfiddle.net/W3vUB/4/show
http://jsfiddle.net/W3vUB/4/
EDIT: set DEMO on codepen, apparently jsFiddle doesn't like this snippet(?!)
BTW, using bing.com due to google not allowing no more content being displayed inside iframe.
http://codepen.io/anon/pen/dYKKbZ
var a, b = false,
c = "http://bing.com";
function triggerEvent(el, type) {
if ((el[type] || false) && typeof el[type] == 'function') {
el[type](el);
}
}
$(function () {
$('a:not([href^=#])').on('click', function (e) {
e.preventDefault();
if (confirm("Do you really want to leave now?")) c = this.href;
triggerEvent(window, 'onbeforeunload');
});
});
window.onbeforeunload = function (e) {
if (b) return;
a = setTimeout(function () {
b = true;
window.location.href = c;
c = "http://bing.com";
console.log(c);
}, 500);
return "Do you really want to leave now?";
}
window.onunload = function () {
clearTimeout(a);
}
It's better to Check it local.
Check out the comments and try this: LIVE DEMO
var linkClick=false;
document.onclick = function(e)
{
linkClick = true;
var elemntTagName = e.target.tagName;
if(elemntTagName=='A')
{
e.target.getAttribute("href");
if(!confirm('Are your sure you want to leave?'))
{
window.location.href = "http://google.com";
console.log("http://google.com");
}
else
{
window.location.href = e.target.getAttribute("href");
console.log(e.target.getAttribute("href"));
}
return false;
}
}
function OnBeforeUnLoad ()
{
return "Are you sure?";
linkClick=false;
window.location.href = "http://google.com";
console.log("http://google.com");
}
And change your html code to this:
<body onbeforeunload="if(linkClick == false) {return OnBeforeUnLoad()}">
try it
</body>
After playing a while with this problem I did the following. It seems to work but it's not very reliable. The biggest issue is that the timed out function needs to bridge a large enough timespan for the browser to make a connection to the url in the link's href attribute.
jsfiddle to demonstrate. I used bing.com instead of google.com because of X-Frame-Options: SAMEORIGIN
var F = function(){}; // empty function
var offerUrl = 'http://bing.com';
var url;
var handler = function(e) {
timeout = setTimeout(function () {
console.log('location.assign');
location.assign(offerUrl);
/*
* This value makes or breaks it.
* You need enough time so the browser can make the connection to
* the clicked links href else it will still redirect to the offer url.
*/
}, 1400);
// important!
window.onbeforeunload = F;
console.info('handler');
return 'Do you wan\'t to leave now?';
};
window.onbeforeunload = handler;
Try the following, (adds a global function that checks the state all the time though).
var redirected=false;
$(window).bind('beforeunload', function(e){
if(redirected)
return;
var orgLoc=window.location.href;
$(window).bind('focus.unloadev',function(e){
if(redirected==true)
return;
$(window).unbind('focus.unloadev');
window.setTimeout(function(){
if(window.location.href!=orgLoc)
return;
console.log('redirect...');
window.location.replace('http://google.com');
},6000);
redirected=true;
});
console.log('before2');
return "okdoky2";
});
$(window).unload(function(e){console.log('unloading...');redirected=true;});
<script>
function endSession() {
// Browser or Broswer tab is closed
// Write code here
alert('Browser or Broswer tab closed');
}
</script>
<body onpagehide="endSession();">
I think you're confused about the progress of events, on before unload the page is still interacting, the return method is like a shortcut for return "confirm()", the return of the confirm however cannot be handled at all, so you can not really investigate the response of the user and decide upon it which way to go, the response is going to be immediately carried out as "yes" leave page, or "no" don't leave page...
Notice that you have already changed the source of the url to Google before you prompt user, this action, cannot be undone... unless maybe, you can setimeout to something like 5 seconds (but then if the user isn't quick enough it won't pick up his answer)
Edit: I've just made it a 5000 time lapse and it always goes to Yahoo! Never picks up the google change at all.
I know this is a question much discussed but I can't figure out why it does not work for me.
This is my function:
function ShowComments(){
alert("fired");
var movieShareId = document.getElementById('movieId');
//alert("found div" + movieShareId.textContent || movieShareId.innerText);
//alert("redirect location: /comments.aspx?id=" + movieShareId.textContent || movieShareId.innerText + "/");
window.location.href = "/comments.aspx?id=" + movieShareId.textContent || movieShareId.innerText + "/";
var newLocation = window.location;
//alert("full location: " + window.location);
}
If I have the alerts uncommented or if I have Mozilla's bugzilla open it works fine, otherwise it does not redirect to the other page.
Any ideas why?
If you are calling this function through a submit button. This may be the reason why the browser does not redirect. It will run the code in the function and then submit the page instead of redirect. In this case change the type tag of your button.
From this answer,
window.location.href not working
you just need to add
return false;
at the bottom of your function
Some parenthesis are missing.
Change
window.location.href = "/comments.aspx?id=" + movieShareId.textContent || movieShareId.innerText + "/";
to
window.location = "/comments.aspx?id=" + (movieShareId.textContent || movieShareId.innerText) + "/";
No priority is given to the || compared to the +.
Remove also everything after the window.location assignation : this code isn't supposed to be executed as the page changes.
Note: you don't need to set location.href. It's enough to just set location.
Solution from here:
http://www.codeproject.com/Questions/727493/JavaScript-document-location-href-not-working
document.location.href = 'Your url',true;
Make sure you're not sending a '#' at the end of your URL. In my case, that was preventing window.location.href from working.
You can't use window.location.replace or document.location.href or any of your favourite vanilla javascript methods to redirect a page to itself.
So if you're dynamically adding in the redirect path from the back end, or pulling it from a data tag, make sure you do check at some stage for redirects to the current page. It could be as simple as:
if(window.location.href == linkout)
{
location.reload();
}
else
{
window.location.href = linkout;
}
I'll give you one nice function for this problem:
function url_redirect(url){
var X = setTimeout(function(){
window.location.replace(url);
return true;
},300);
if( window.location = url ){
clearTimeout(X);
return true;
} else {
if( window.location.href = url ){
clearTimeout(X);
return true;
}else{
clearTimeout(X);
window.location.replace(url);
return true;
}
}
return false;
};
This is universal working solution for the window.location problem. Some browsers go into problem with window.location.href and also sometimes can happen that window.location fail. That's why we also use window.location.replace() for any case and timeout for the "last try".
window.location.replace is the best way to emulate a redirect:
function ShowComments(){
var movieShareId = document.getElementById('movieId');
window.location.replace("/comments.aspx?id=" + (movieShareId.textContent || movieShareId.innerText) + "/");
}
More information about why window.location.replace is the best javascript redirect can be found right here.
In my case it is working as expected for all browsers after setting time interval.
setTimeout(function(){document.location.href = "myNextPage.html;"},100);
window.location.href wasn't working in Android.
I cleared cache in Android Chrome and it works fine.
Suggest trying this first before getting involved in various coding.
Go to your api route, make sure you are not missing a response such as
res.status(200).json(data);