I am trying to refresh the page only one time when a particular URL is hit.
The reason for this is to refresh the data on the view. My URL is
http://localhost:8072/web?#min=1&limit=80&view_type=list&model=pos.order&action=405
And solutions I have tried are
window.onload = function() {
//considering there aren't any hashes in the urls already
if(!window.location.hash) {
//setting window location
window.location = window.location + '#loaded';
//using reload() method to reload web page
window.location.reload();
}
}
(function()
{
if( window.localStorage )
{
//check if reloaded once already
if( !localStorage.getItem('firstLoad') )
{
//if not reloaded once, then set firstload to true
localStorage = true;
//reload the webpage using reload() method
window.location.reload();
}
else
localStorage.removeItem('firstLoad');
}
})();
$(document).ready(function(){
//Check if the current URL contains '# or hash'
if(document.URL.indexOf("#")==-1){
// Set the URL to whatever it was plus "#loaded".
url = document.URL+"#loaded";
location = "#loaded";
//Reload the page using reload() method
location.reload(true);
}
});
None of them worked for me. What is wrong or which direction should I choose?
Your first solution works fine, it just needed a return statement to prevent execution the rest of the code, however if your original url contains a hash, you can do the check like this:
window.onload = function() {
document.getElementById("test").textContent = window.location;
console.log(window.location.hash);
//check for our specific hash argument
if (!window.location.hash.match(/[#&]loaded(&|$)/)) {
alert("the page is about to refresh");
//setting window location
window.location = window.location + (window.location.hash ? "&" : "#") + 'loaded';
//using reload() method to reload web page
window.location.reload();
return;
}
alert("page refreshed");
}
<div id="test"></div>
Related
Almost have it, but might need a hand :
I created a script to redirect AND set a cookie that comes in from ANY page from our site. So even if a user comes in from a direct link to a news article, it will redirect them to our "splash" page and set a "cookie" to avoid further redirects. I have that part working perfect.
$(document).ready(function() {
if (typeof Cookies.get('secondvisit') === 'undefined') {
window.location.href = "/index-donate.php";
}
})
However, we now want to capture the URL that they came to first and create a variable so we can have them be linked back to that page after they read our SPLASH page.
So in the example above:
Come in via direct link: /news/article1.php
No cookie is detected, so we first need to "capture" the page they came in on "$page-refer" and then redirect them to our Splash page.
On the splash page, we would then present a LINK to them with "Proceed to webpage" with the "$page-refer" link.
I did try this ( BELOW ), but this is only grabbing the "google" page and not OUR webpage that they hit first.
Thanks!
$(document).ready(function() {
if (typeof Cookies.get('secondvisit') === 'undefined') {
var referringURL = document.referrer;
var local = referringURL.substring(referringURL.indexOf("?"), referringURL.length);
location.href = "/index-donate.php" + local;
}
})
I think you could add the URL as a cookie when you do the redirect, ex:
$(document).ready(function () {
if (typeof Cookies.get('secondvisit') === 'undefined') {
Cookies.set('initialvisitedpage', window.location.href);
window.location.href = "/index-donate.php";
}
});
then you could redirect them to the cookie value:
$(document).ready(function() {
if (typeof Cookies.get('secondvisit') === 'undefined') {
window.location.href = Cookies.get('initialvisitedpage') || '/'; // or whatever this could default to in case they don't have the cookie
}
})
Put together an answer that works great, thanks for the comments and push:
On footer script template:
$(document).ready(function () {
if (typeof Cookies.get('secondvisit') === 'undefined') {
location.href = "/index-donate.php?page-refer=" + encodeURIComponent(location.href);
}
})
Then on my Splash page:
I captured the variable $pageredirect via $_GET['page-refer'] and then presented that as a link further down the page ( if set )!
this.testing = function(link) {
window.location = link;
window.addEventListener('load', function() {
alert("It's loaded!");
});
//OR
myFunctionCall()
}
This is the code I'm trying to implement but after the window is redirected to a link Im not getting the alert.
My aim is to call a function which is dependent on the window after getting redirected
I have used history.pushState() and now if the user refreshes the page then it is refreshing current URL which is not an original URL.
I tried detecting refresh page with a cookie, hidden filed but it is not working.
window.onload = function() {
document.cookie="PR=0";
var read_cookies = document.cookie;
var s = read_cookies;
s = s.substring(0, s.indexOf(';'));
if( s.includes("1"))
{
window.location.href = "https://www.google.com";
}
else{
document.cookie="PR=1";
}
loadURL();
};
function loadURL()
{
document.cookie="PR=1";
document.getElementById("visited").value="1";
var str="abc/b cd";
str=str.replace(/ /g, "-");
history.pushState({},"",str);
}
when user is refreshing the page I need original URL on that time.
This might be helpful. But you need control over the pushed url.
// this goes to your 'original' url
window.addEventListener('beforeunload', function (event) {
sessionStorage.setItem('lastPage', window.location.href)
}
// page with your pushed url
if (sessionStorage.getItem('lastPage') === 'PAGE_YOU_DONT_WANT_TO_BE_REACHABLE_DIRECTLY') {
window.location = 'PAGE_YOU_WANT'
}
I'm interested what the use case for this is. As far as my knowledge goes you can't suppress the refresh event completely.
I want to toggle between two jQuery functions. It has to be done on page load - and each page load should only execute one of the scripts.
This is what I got so far:
HTML:
<button class=".click">Click me</button>
Script:
$(function() {
if (window.location.href.indexOf("addClass") > -1) {
$("body").addClass("test");
}
else {
$("body").addClass("secondtest");
}
$('.click').on('click', function() {
console.log("Clicked");
var url = window.location.href;
if (url.indexOf('?') > -1) {
url += '?param=addClass'
} else {
url += '?param=1'
}
window.location.href = url;
});
});
This Gets me a bit on the way, the first click adds ?param=1 on the first click - nothing happens - second click it adds the ?param=addClass and the body gets the class. If I click again it adds ?param=addClass every time.
I want one of the script to run as default - then I want the first button click to reload and run the other script instead. If I click once more I want it to reverse the url so the first script loads, like a toggle.
I now there is an easy way to just toggle classes, but I specifically need to run one of two scripts on a new page load.
Update:
$(function() {
if (window.location.href.indexOf("addClass") > -1) {
$("body").addClass("test");
}
else {
$("body").addClass("secondtest");
}
$('.click').on('click', function() {
console.log("Clicked");
var url = window.location.pathname;
var url = window.location.href;
if (url.indexOf('?param=1') > -1) {
url = url.replace("param=1", "")+'param=addClass'
} else {
url = url.replace("?param=addClass", "")+'?param=1'
}
window.location.href = url;
});
});
This set the body class on first page load - then first click ads ?param=1 but doesnt change the body class. Second click replaces ?param=1 with ?param=addClass and changes the body class - after that the toggles works. So How do I make it work from the first click?
This will be the default functionality, if no query string is present then add ?param=1:
var url = window.location.href;
if(url.indexOf('?param=1')==-1 )
{
window.location.href = url+"?param=1";
}
This will be the onclick functionality to toggle the urls as it is replacing the existing functionality.
$('.click').on('click', function() {
var url = window.location.href;
if (url.indexOf('?param=1') > -1) {
url = url.replace("param=1", "")+'param=addClass'
} else {
url = url.replace("?param=addClass", "")+'?param=1'
}
window.location.href = url;
});
If you want to toggle the classes as well you can use .toggleClass("test secondtest")
The issue you have is in this if:
var url = window.location.href;
if (url.indexOf('?') > -1) {
url += '?param=addClass'
} else {
url += '?param=1'
}
Scenario 1: /test.html
indexOf('?') will be negative. You will then redirect the user to /test.html?param=1
Scenario 2: /test.html?param=1
indexOf('?') will then be positive. You will then redirect the user to /test.html?param=1?param=addClass
Scenario 3: /test.html?param=addClass
indexOf('?') will then be positive. You will then redirect the user to /test.html?param=addClass?param=addClass
So... what is wrong?
You are using window.location.href. Excellent for setting the path but bad if you want to actually manage the query parameters.
Solution
var url = window.location.pathname;
var hasParams = window.location.href.indexOf('?') > -1;
if (hasParams) {
url += '?param=addClass'
} else {
url += '?param=1'
}
window.location.href = url;
Since you are redirecting on the same host (seen with your code), you only need the pathname. pathname doesn't include parameters (?key=value&...) and can be used to redirect a user on the same domain.
HTML
<div class="moreButton">
<a class="more" id="<?php echo htmlspecialchars($page);?>">More</a>
</div>
AJAX
$(function(){
$('.more').live('click', function(){
var page = $(this).attr('id'); //get the last id
$.ajax({
type : 'GET',
url : 'functionality/js/paginate.php',
data : { page : page, per_page : per_page, last_page : last_page },
beforeSend: function(){
$('.more').html(img);
if(history.pushState){
history.pushState(null, null, '#' + page);
}else{
location.hash = '#' + page;
}
},
success: function(data){
$('.more').remove();
$('.main-content').append(data);
}
});
});
});
I've implemented a load_more style of pagination. The problem here is the usual for infinite scrolls, when a user clicks a post and comes back with back button, he/she should get the previous number of loaded posts, but only initial posts are loaded. I'm trying to integrate the history.pushState functionality based on what I found googling, but doesn't seem to get it working. What am I missing here?
There are two key parts to saving states using browser history. The pushState function allows you to add to the history stack (essentially like going to a new page). It also allows you to store a javascript object as the "state". This will come in handy when the state is "popped" off the stack (e.g. the browser's "back" button is pressed).
Browsers throw a popstate event which you can use to determine if the browser is going back to a previous state. You can access it with window.onpopstate. To watch for a hash change you can use window.onhashchange.
if ("onpopstate" in window) {
window.onpopstate = function (event) {
if (event.state && event.state.pageID) {
fetchData(event.state.pageID);
}
};
}
if ("onhashchange" in window) {
window.onhashchange = function () {
if (location.hash) {
fetchData(location.hash.substr(1));
}
};
}
function fetchData(pageID) {
// Load some content
}
function saveState(pageID) {
if (history.pushState) {
history.pushState({ pageID: pageID }, null, "/page/" + pageID);
} else {
location.hash = pageID;
}
}
Here you need to define a function to check hash update as if hash updates(User clicks on back/forward button) it should update data of the page according to URL.