Call history.back() without triggering 'popstate' - javascript

Is there a way to call window.history.back(); without triggering this.getWindow().on('popstate', this.handleBrowserButtons.bind(this));?

No, window.history.back and window.history.go would always trigger the popstate event.
In fact, that's the only time the event is actually triggering so you could probably remove the popstate event handler altogether and use something else if you don't want this happening on back/forward navigation.

As history.back and history.go always call a registered onpopstate event you could make the onpopstate event the main way of closing the modal. I did this when I was doing something similar and it worked well.
To keep this backward compatible with browsers that don't support pushstate you can check for support and call closeModal directly when there is no support.
So the close modal button code would be like this:
if (history.pushState) {
// Your popstate event handler will be called, which calls closeModal()
history.back();
}
else {
// No popstate event handler registered, so call closeModal() directly
closeModal();
}

Related

Stop propagation doesn't work

I have the below JQuery eventhandler. I want to stop all navigations on a web page.
$(document).click(function(event) {
event.stopPropagation();
event.preventDefault();
event.cancelBubble = true;
event.stopImmediatePropagation();
$(document).css('border-color','');
$(document).css('background-color','');
$(event.target).css('border-color','yellow');
$(event.target).css('background-color','#6BFF70');
return false;
});
When I use this on Facebook Login page, it stops all navigations. But in Google home page, "I'm Feeling Lucky" button still navigates to next page. How do I avoid it?
I'm using JavaFX browser by the way. It is similar to Safari browser.
If I load the Google search page, and execute this at the console:
document.body.addEventListener(
"click",
function (ev) { ev.stopPropagation(); ev.preventDefault(); },
true);
then I cannot click the "I'm Feeling Lucky" button anymore. The key is to use the third parameter and set it to true. Here is what MDN [says] about it:
useCapture Optional
If true, useCapture indicates that the user wishes to initiate capture. After initiating capture, all events of the specified type will be dispatched to the registered listener before being dispatched to any EventTarget beneath it in the DOM tree.
(Emphasis added.)
What you tried to do does not work because your event handler is on document, and thus will be called after any event handlers on the children of the document. So your handler cannot prevent anything.
With useCapture set to true, you can operate on the event before it gets a chance to be passed to the child element. I do not know of a way to have jQuery's event handlers work in the way you get with useCapture. Barmar's answer here says you can't use jQuery to set such handler. I'm inclined to believe him.
99.99% of webpages won't be able to have their navigation stopped by stopping event propagation for the reason I commented (you can't stop the event before it triggers all handlers for the initial target of the event). If preventing navigation is all you are interested in, I recommend using the window.onbeforeunload event, which is made for this exact situation.
Here is an example: http://jsfiddle.net/ejreseuu/
HTML:
google
JS:
window.onbeforeunload = function() {
return "Are you sure?"
}
There is no way to not have a confirmation box that I know of, as code that locks the user out of navigating away no matter what they do is generally malicious.
preventDefault() should not work in this case, cause Google relied on custom event listeners to handle click events on this button. While preventDefault()
prevents browser's default behavior.
For example, if this button was of type="submit", preventing default on click event would prevent browser's default behavior, which is submitting a form. But in this case click is handled by eventListeners added to the button itself. preventDefault() won't affect catching an event by them. Nor stopPropagation(), because it stops propagation of event to higher levels of DOM, while other eventListeners on the same level (button in our case) still get the event. stopImmediatePropagation() could work in theory, but only if your eventListener was added before google's.
So the easiest way to stop propagation is to stop an event before it reaches button node, and that's on capture phase, because button is the lowest element in the hierarchy. This can be done by passing true argument while adding eventListener
document.body.addEventListener("click", function (event) {
event.stopPropagation();
}, true);
This way event will be stopped before bubble phase, and so before it reaches eventListeners added to the button. More on capture and bubble phases here
Note that preventDefault() is not needed in this case. Actually, this button's event listeners are to prevent default themselves. Here are those eventListeners, for click and keyup respectively:
d = function(a) {
c.Xa.search(c.yc(), b);
return s_1vb(a)
}
function(a) {
13 != a.keyCode && 32 != a.keyCode || d(a)
}
note call to s_1vb, here is its sourse:
s_1vb.toString();
/*"function (a){
a&&(a.preventDefault&&a.preventDefault(),a.returnValue=!1);
return!1
}"*/
Basically its a function that take an event and do everything possible to prevent browser's default behavior
By the way, default behavior can be canceled on any stage of event flow (se Events Specification), including the very last stage, when it reached document. Only after it passed "through" all eventListeners uncanceled, browser should execute its default behavior. So attaching your listener to document was not the reason preventDefault() didn't work, it was because it was the wrong guy for the job :)
Try this:
$('body').click(function(event) {
event.stopPropagation();
event.preventDefault();
event.cancelBubble = true;
event.stopImmediatePropagation();
$(document).css('border-color','');
$(document).css('background-color','');
$(event.target).css('border-color','yellow');
$(event.target).css('background-color','#6BFF70');
return false;
});
Try to bind not only to click event, but as well on mousedown event.
Try this css:
body * {
pointer-events: none;
}
or in jQuery:
$("body *").css("pointer-events", "none");
Try declaring a new window event and then stopping the propagation from there:
var e = window.event;
e.cancelBubble = true;
if (e.stopPropagation)
{
e.stopPropagation();
}
Note that Google uses jsaction="..." instead of onclick="...". Try to use it's unbind method on the specified button.
Also you can use dynamic attachment, like:
$(document).on('click', '*', function
Or throw new Error()(just as a dirty hack)

Is there a way to delay a popstate event?

I've tried a few methods to see if I can create a cross browser solution for delaying a popstate event but have not had any luck.
Anyone have any ideas or thoughts?
Below obviously does not work, but something to the effect of:
$(window).on('popstate', function(e) {
// something here to delay the history pageload
console.log('a wild console has appeared!');
});
So the flow would follow this sequence:
Browser "back" or "forward" button clicked
run initial code
A delay before the page changes
page change
According to the Documentation the popstate event is
only triggered by doing a browser action such as a click on the back button
So I do not believe it will get triggered when user clicks 'forward' (and it varies in some browsers)
For reference, here's the full text:
The popstate event is fired when the active history entry changes. If the history entry being activated was created by a call to history.pushState() or was affected by a call to history.replaceState(), the popstate event's state property contains a copy of the history entry's state object.
Note that just calling history.pushState() or history.replaceState() won't trigger a popstate event. The popstate event is only triggered by doing a browser action such as a click on the back button (or calling history.back() in JavaScript).
Browsers tend to handle the popstate event differently on page load. Chrome (prior to v34) and Safari always emit a popstate event on page load, but Firefox doesn't.
UPDATED ANSWER ABOVE
Your code works. (see below) - I added an element to trigger the event (you can see the results in the console)
Make sure you include the jQuery library on your HTML prior to using it though.
$(window).on('popstate', function(e) {
console.log('fired instantly!');
var timer = setTimeout(function() {
console.log('delayed popstate!');
clearTimeout(timer);
}, 1000);
});
$(window).trigger( 'popstate') ;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

popstate event on history api does not fire

I have a simple code to test the history api of html5
Just some buttons
<button name="hey1" onClick="historytestone();">history test one</button>
<button name="hey2" onClick="historytesttwo();">history test two</button>
<button name="hey3" onClick="historytestthree();">history test three</button>
<button name="hey4" onClick="historytestfour();">history test four</button>
<button name="hey5" onClick="historytestfive();">history test five</button>
and my js is like
function historytestone(){
history.pushState({page: "ross"}, "ross","ross.html");
}
function historytesttwo(){
history.pushState({page: "monica"}, "monica","monica.html");
}
function historytestthree(){
history.pushState({page: "chandler"}, "chandler","chandler.html");
}
function historytestfour(){
history.pushState({page: "joy"}, "joy","joy.html");
}
function historytestfive(){
history.pushState({page: "rachel"}, "rachel","rachel.html?a=1&b=2");
}
// this does not work
window.addEventListener("popstate", function(event) {
alert("hello");
});
//nor this works
window.onpopstate=function(event){
alert("hello");
}
When I try to listen for the popstate event, I get no alert and no errors on the console. No metter what syntax I use, I get nothing.
Sorry, but I cannot see what is wrong. Please explain.
EDIT
Here is my problem.
This is my code here and this is the demo I was based here.
Now, I believe that my code is a simplified version of the demo.
I have to click the "back" button of the browser in order to fire the popstate event (see the alerts). But the demo can fire the popstate event (change content) just by clicking the names.
Why this happens? Why I have to hit the back button and the demo does not, even tho is the same code? Thanks again
based on the definition here: https://developer.mozilla.org/en-US/docs/Web/Events/popstate
The popstate event is fired when the active history entry changes. If
the history entry being activated was created by a call to
history.pushState() or was affected by a call to
history.replaceState(), the popstate event's state property contains a
copy of the history entry's state object.
Note that just calling history.pushState() or history.replaceState()
won't trigger a popstate event. The popstate event is only triggered
by doing a browser action such as a click on the back button (or
calling history.back() in JavaScript).
Browsers tend to handle the popstate event differently on page load.
Chrome and Safari always emit a popstate event on page load, but
Firefox doesn't.
if you see the source code of http://html5doctor.com/demos/history/ each time when you click a link it calls the updateContent function (which is also the event handler of popstate) then it calls pushState.

popstate event handler seems not to work

I'm having a problem with a 'popstate' event handler, this is my code:
window.addEventListener("popstate", function (event){
if (event.state) {
alert('abc')
}
});
// The data object is arbitrary and is passed with the popstate event.
var dataObject = {
createdAt: '2011-10-10',
author: 'donnamoss'
};
var url = '/posts/new-url';
history.pushState(dataObject, document.title, url);
I expected this code will pop up an alert box when it's executed but, nothing happens.
Is there anything wrong here?
Thank you.
pushState do not trigger the popstate event, only clicking back / forward button (or use backspace) or invoking history.back() / history.go(n) would trigger this event.
Also, in webkit browsers, a popstate event would be triggered after page's onload event, but Firefox and IE do not have this behavior.
No it will not,
As per MDN documentation
Note that just calling history.pushState() or history.replaceState() won't trigger a popstate event. The popstate event is only triggered by doing a browser action such as a click on the back button (or calling history.back() in JavaScript).
Again as per this question the popstate event is not triggered in Chrome when you call pushState().
history.pushState() will not trigger the popstate event by definition.
The popstate event is fired in certain cases when navigating to a session history entry.
This event is intended to be only triggered when navigating to a history entry, either by pressing the back/forward button, or history.go/back.

preventDefault() doesn't prevent the action

When I use event.preventDefault() on a link it works, however when I use it on a button doesn't!
DEMO
My code:
<a id="link" href="http://www.google.com">link</a>
<button id="button" onclick="alert('an alert')">button</button>​
$('#link').click(function(event){
event.preventDefault();
});
$('#button').click(function(event){
event.preventDefault();
});
​
Link action is cancelled, but when I click on the button, still executes the onClick action.
Any help? what I want to do is to prevent the button onClick action without changing the button html (I know how to do
$('#button').removeAttr('onclick');
You want event.stopImmediatePropagation(); if there are multiple event handlers on an element and you want to prevent the others to execute. preventDefault() just blocks the default action (such as submitting a form or navigating to another URL) while stopImmediatePropagation() prevents the event from bubbling up the DOM tree and prevents any other event handlers on the same element from being executed.
Here are some useful links explaining the various methods:
http://api.jquery.com/event.preventDefault/
http://api.jquery.com/event.stopPropagation/
http://api.jquery.com/event.stopImmediatePropagation/
However, since it still doesn't work it means that the onclick="" handler executes before the attached event handler. There's nothing you can do since when your code runs the onclick code has already been executed.
The easiest solution is completely removing that handler:
$('#button').removeAttr('onclick');
Even adding an event listener via plain javascript (addEventListener()) with useCapture=true doesn't help - apparently inline events trigger even before the event starts descending the DOM tree.
If you just do not want to remove the handler because you need it, simply convert it to a properly attached event:
var onclickFunc = new Function($('#button').attr('onclick'));
$('#button').click(function(event){
if(confirm('prevent onclick event?')) {
event.stopImmediatePropagation();
}
}).click(onclickFunc).removeAttr('onclick');
you need stopImmediatePropagation not preventDefault. preventDefault prevents default browser behavior, not method bubbling.
http://api.jquery.com/event.stopImmediatePropagation/
http://api.jquery.com/event.preventDefault/
The preventDefault function does not stop event handlers from being triggered, but rather stops the default action taking place. For links, it stops the navigation, for buttons, it stops the form from being submitted, etc.
What you are looking for is stopImmediatePropagation.
you can try this:
$('#button').show(function() {
var clickEvent = new Function($(this).attr('click')); // store it for future use
this.onclick = undefined;
});
DEMO
It have helped me
function goToAccessoriesPage(targert) {
targert.onclick.arguments[0].preventDefault();
...
}

Categories