I've run into an interesting issue and I'm not sure how to solve it. I maintain a hidden value on my homepage that tracks the events loaded on the page. The event position gets updated after the page loads. When navigating away from the page and then clicking the browsers back button the previous event number is seen. If I click a link and load the home page directly the event position gets reset (as expected)
My HTML:
<input type="hidden" id="event_num" value="0">
My javascript call to get/set the event_num value:
function getRecentEvents() {
var event_pos = $('#event_num').val();
//console.log("POS: " + event_pos);
$.getJSON("functions/get_events.php", { f: 'get_events', event_pos: event_pos, limit: limit}, function(data) {
if (data.events.length > 0) {
// set the new value
$('#event_num').val(data.events_pos);
}
});
I would expect the hidden field to be 0 every time the page is loaded regardless if the user clicked a link or hit the back button on the browser.
Any idea how I might fix this or is this a known issue?
The page is not loaded again if you click the "back" button, the cached page content is shown. That is, the page as the state of it was the last time you visited it. You could reset the event_num counter on $(document).ready or on a document unload event, then you will get the expected behaviour.
Related
I have a privacy warning dialog that users can either click accept button, click decline button, click close button or click a link on the page to bypass - working with what Im give here. I need to fire a function if a user clicks a link on the page instead of clicking on any of the warning dialog's buttons.
The native unload handler gets blocked in some cases and also fires on page refresh. The hashchange event doesn't work as Im not using hashed urls. So I'm trying to capture the first page pathname, then on unload compare to the new page pathname and if they aren't equal run a function. Something isn't right here:
var origURL = window.location.pathname.slice(1);
$(window).unload(function(){
var newURL = window.location.pathname.slice(1);
if($(origURL) != (newURL)){
//run function if page changes
} else {
//page hasn't changed - do nothing
}
})
Is there a better way to detect page change? I can't attach to a click event, as some links are done w/JS and not on an anchor.
So I'm running a data collection project by injecting a html form into a third party website, via a chrome extension, which instructs users to describe the data they see and submit it to my server.
For some bizarre reason, however, whenever the user clicks the "submit" button to send the form contents to the background page (and from thence to the server), the underlying page reloads, and, not only that, but it reloads with the contents of the form I injected showing up in the url after reload. Which is kind of bizarre behavior.
I don't know if this is something in my code, or even if it's something in the underlying web page's code (maybe it redefines chrome.runtime.sendMessage or something as some kind of anti-extension technique?!!?). I'd really like to stop this behavior if possible... does anyone have any ideas?
The relevant parts of my code, stripped down a little:
var cururl = window.location.href
var codestring= "[A HTML FORM TO INJECT]"
var raformvalues = {};
function codeValues() {
$.each($('#mainCoding').serializeArray(), function(i, field) {
raformvalues[field.name] = field.value;
});
}
function sendValues() {
let pageinfo = {"page": document.documentElement.outerHTML,
"url": cururl,
"title": document.title,
"timestamp": String(Date.now())};
let tosend = $.extend({"type": "doctype"}, pageinfo, raformvalues);
chrome.runtime.sendMessage(tosend);
chrome.storage.local.set({'lasturl': pageinfo.url});
$("#pgcodediv").empty();
location.href = cururl; // note: I added this line to try to stop the reloading and url/changing behavior. behavior is the same with and without it.
}
function appendCodingInfo() {
$("#headerID").append(codestring);
$( ":checkbox, :radio" ).click( codeValues );
$( ":text" ).change( codeValues );
$( "#codingsubmit" ).click(sendValues);
}
appendCodingInfo()
when the user hits the submit button (#codingsubmit, of course), the message gets passed and the background page handles it correctly, but the page refreshes unbidden, and the contents of raformvalues show up in the URL of the refreshed page (i.e., when I call window.location.href from the console the contents of that object show up as parameters to a get request, i.e., http://url?prop=value&prop2=value2 -- no clue why.
If you click a button with type="submit" in a form, by default browser will reload the page after the form is submitted.
To prevent the page reloaded, either replace type="submit" with type="button" or call e.preventDefault() inside sendValues handler.
Appendix:
According to MDN, the default value for button is submit.
type
The type of the button. Possible values are:
submit: The button submits the form data to the server. This is the default if the attribute is not specified, or if the attribute is dynamically changed to an empty or invalid value.
reset: The button resets all the controls to their initial values.
button: The button has no default behavior. It can have client-side scripts associated with the element's events, which are triggered when the events occur.
menu: The button opens a popup menu defined via its designated element.
I'm trying to handle some logic on before unload and I don't want that logic to run if the user is reloading the page or going back.
I've set up something like this.
window.onbeforeunload = function(e) {
if(window.event && window.event.clientX){ //IE
//some logic
} else if (e.currentTarget.performance.navigation.type === e.currentTarget.performance.navigation.TYPE_RELOAD) {
// another logic
} else if(e.currentTarget.performance.navigation.type === e.currentTarget.performance.navigation.TYPE_BACK_FORWARD){
// yet another logic
}
}
I have other code to handle refresh and such from keyboard input that all seems to be working ok. Right now I'm concerned with this piece of code. For some reason on the first reload or back button the navigation.type comes back as 0, but after that all other reloads or back buttons populate the correct value in navigation.type. Even in IE on the first reload something is not being set correctly (not sure if its the mouse location or what yet). What could be causing something like this?
First of all, I think what you wanted to write was e.currentTarget.performance.navigation.type (not e.current.performance.navigation.type), which is the same as writing window.performance.navigation.type. This variable tells you how this page was navigated to, not the type of navigation that the page is exiting through.
Why you get performance.navigation.type as 0 (performance.navigation.TYPE_NAVIGATE) the first time is that the page was loaded by direct navigation that first time. Subsequent reloads will set performance.navigation.type to 1 (performance.navigation.TYPE_RELOAD) because the page is now loaded by reloading. So, you are getting the method that was used to load the page, not the method that the user is using to exit the page.
I have to do some kind of operation on the page refresh or reload. that is when I hit next page or Filter or refresh on the grid. I need to show some confirmation box over this Events.
is there any event which can tell you page is doing filer? refresh or paging? using javascript?
Thanks
If it is refreshing (or the user is leaving the website/closing the browser), window.onunload will fire.
// From MDN
window.onunload = unloadPage;
function unloadPage()
{
alert("unload event detected!");
}
https://developer.mozilla.org/en/DOM/window.onunload
If you just want a confirmation box to allow them to stay, use this:
window.onbeforeunload = function() {
return "Are you sure you want to navigate away?";
}
You can create a hidden field and set its value on first page load. When the page is loaded again, you can check the hidden field. If it's empty then the page is loaded for the first time, else it's refreshed. Some thing like this:
HTML
<body onLoad="CheckPageLoad();">
<input type="hidden" name="visit" id="visit" value="" />
</body>
JS
function CheckPageLoad() {
if (document.getElementById("visit").value == "") {
// This is a fresh page load
document.getElementById("visit").value = "1";
}
else {
// This is a page refresh
}
}
There are some clarification notes on wrestling with this I think are critical.
First, the refresh/hidden field system works on the beginning of the new page copy and after, not on leaving the first page copy.
From my research of this method and a few others, there is no way, primarily due to privacy standards, to detect a refresh of a page during unload or earlier. only after the load of the new page and later.
I had a similar issue request, but basically it was terminate session on exit of page, and while looking through that, found that a browser treats a reload/refresh as two distinct pieces:
close the current window (fires onbeforeunload and onunload js events).
request the page as if you never had it. Session on server of course has no issue, but no querystring changes/added values to the page's last used url.
These happen in just that order as well. Only a custom or non standard browser will behave differently.
$(function () {
if (performance.navigation.type == 1) {
yourFunction();
}
});
More about PerformanceNavigation object returned by performance.navigation
I have a button which acts as an indicator, so has two states; pressing it toggles the state, and moves on to the next page.
Pressing the button calls a JavaScript function which handles this.
Having changed a button's 'src' image, using jQuery, I wish for the user to see the image change, pause for a fraction of a second, and only then see the next page displayed.
I am finding that the image does not visibly change until the JavaScript function returns, but this is after the pause, and after the page change. I.e. the browser does not show the page changes until the button's function has exit.
So I wish to cause the page to repaint in the browser, before the pause.
All the solutions I have tried refresh the page to its state on the server, and any changes I made to it in jQuery are lost.
Is there a way to force the page or button to be repainted, which will honor the changes I made to it in JavaScript/jQuery?
$("#YourButtonWhichTriggersChanges").click(function() {
// page repaint code, image change, etc.
setTimeout(function(){
window.location.reload();
// use window.location.href = "my/new/url.html";
// or window.location.replace("my/new/url.html");
// to change the page instead of just reloading.
}, 1000);
});
Where 1000 is the number of milliseconds you want to wait before refreshing the page.
Edit: I think you want this code instead:
$("#ApproveButton").css('backgroundImage', 'url(\'img/but/proof/ApprovePageButton.png\')');
The extra backslashes are in there to escape out the single quotes in the url parameter.
Another edit: Here's a combination of the two solutions I supplied which should work:
$("#ApproveButton").click(function() {
// actually repaint the button's background image
$(this).css('backgroundImage', 'url(\'img/but/proof/ApprovePageButton.png\')');
// change the page after 1000 milliseconds have gone by.
setTimeout(function(){
window.location.reload();
/* use window.location.href = "my/new/url.html";
* or window.location.replace("my/new/url.html");
* to change the page instead of just reloading.
*/
}, 1000);
});