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);
Related
I need all blog product pages to show in a popup. In order to show in the popup their url must be in the form https://expample.com?/modal-link=blog_page_url. (I'm using the plugin and this is the requirement)
I would like to write a code in javascript that checks the URL. If the URL of the page contains the word 'product' I would like prepend to the url: https://expample.com?/modal-link= inorder to enable it to be shown in a popup.
I'm using the code below:
if(window.location.href.indexOf("product") > -1) {
var url = window.location.href;
url_new = 'https://example.com/?modal-link=' + url
} else {
}
window.location.href = url_new;
The is creating a new URL but it is causing it to be added an infinite amount of time.
How should I be doing this?
Follow on question: (should I open a new question for this?)
I would like to adapt the code so the page does not reload during the redirect.
I know there are other posts about this eg How do I modify the URL without reloading the page? or https://stackoverflow.com/questions/3338642/updating-address-bar-with-new-url-without-hash-or-reloading-the-pagebut could someone please help me modify my javascript code for this specific case?
Would I need to use the lines below?
document.location.hash = 'afterhash';
history.pushState('data to be passed', 'Title of the page', '/test');
I'm at a loss which part of my code need to go where in the above lines.
Your recursion is missing a stop condition. For example, if "some_product" contains "product" and you prepend anything to it, it will still contain "product", as in "really_some_product", "really_really_some_product", etc. You can see where this is going, infinite recursion.
So, you need to tell it to stop at some point, which is when the new url already starts with what you intend to prepend to the original one.
Following this, since there's a case in which we don't change anything, we should also not redirect.
var url = window.location.href,
prepend_to_url = "https://example.com/?modal-link=",
url_new = false;
if (url.indexOf(prepend_to_url) == 0) {
// url starts with what we prepend
// so do nothing
} else if(url.indexOf("product") > -1) {
url_new = prepend_to_url + url;
}
if (url_new) { // don't redirect unless we've done something above
window.location.href = url_new;
}
A more concise version of the code above could look like this:
var url = window.location.href,
prepend_to_url = "https://example.com/?modal-link=",
url_new = false;
if (url.indexOf(prepend_to_url) == -1 // url doesn't start with what we prepend
&& url.indexOf("product") > -1 // and our condition is met
) {
url_new = prepend_to_url + url;
}
url_new && (window.location.href = url_new); // equivalent to an "if" statement
What you need is to get the query parameter part of the url by using substr with index of ? to the end of the url
var url_new;
if(window.location.href.indexOf("product") > -1) {
var url = window.location.href.substr(window.location.href.indexOf("?") +1, window.location.href.length);
var newValue = 10;
url_new = 'https://example.com/?modal-link=' + newValue + "&" + url
}
console.log(url_new);
You should initilize the url_new and change it for some condition:
let url_new = window.location.href
if(window.location.href.indexOf("product") > -1) {
url_new = 'https://example.com/?modal-link=' + window.location.href;
}
window.location.href = url_new;
I want to reload my html page just after it loads for the first time, but not to reload if page is refreshed. What I have done is:
window.onload = function() {
if(!window.location.hash) {
window.location = window.location + '#loaded';
window.location.reload();
}
}
But with this approach if I refresh the page it gets reloaded which I don't want. Are there any solutions to avoid this? Thanks in advance.
Use localStorage to achieve this.
Try:
alert("page load")
if(localStorage.getItem("reload") != "1"){
localStorage.setItem("reload","1");
window.location.href = window.location.href;
}
else{
localStorage.removeItem("reload");
}
This will do it, but how do you prevent reloading on all browsers but Firefox?
if (window.location.href.toLowerCase().indexOf("loaded") < 0) {
window.location = window.location.href + '?loaded=1'
}
Try setting the cookie and check
Could someone please share experience / code how we can detect the browser back button click (for any type of browsers)?
We need to cater all browser that doesn't support HTML5
The 'popstate' event only works when you push something before. So you have to do something like this:
jQuery(document).ready(function($) {
if (window.history && window.history.pushState) {
window.history.pushState('forward', null, './#forward');
$(window).on('popstate', function() {
alert('Back button was pressed.');
});
}
});
For browser backward compatibility I recommend: history.js
In javascript, navigation type 2 means browser's back or forward button clicked and the browser is actually taking content from cache.
if(performance.navigation.type == 2) {
//Do your code here
}
there are a lot of ways how you can detect if user has clicked on the Back button. But everything depends on what your needs. Try to explore links below, they should help you.
Detect if user pressed "Back" button on current page:
Is there a way using Jquery to detect the back button being pressed cross browsers
detect back button click in browser
Detect if current page is visited after pressing "Back" button on previous("Forward") page:
Is there a cross-browser onload event when clicking the back button?
trigger event on browser back button click
Found this to work well cross browser and mobile back_button_override.js .
(Added a timer for safari 5.0)
// managage back button click (and backspace)
var count = 0; // needed for safari
window.onload = function () {
if (typeof history.pushState === "function") {
history.pushState("back", null, null);
window.onpopstate = function () {
history.pushState('back', null, null);
if(count == 1){window.location = 'your url';}
};
}
}
setTimeout(function(){count = 1;},200);
In case of HTML5 this will do the trick
window.onpopstate = function() {
alert("clicked back button");
}; history.pushState({}, '');
You can use this awesome plugin
https://github.com/ianrogren/jquery-backDetect
All you need to do is to write this code
$(window).load(function(){
$('body').backDetect(function(){
// Callback function
alert("Look forward to the future, not the past!");
});
});
Best
In my case I am using jQuery .load() to update DIVs in a SPA (single page [web] app) .
Being new to working with $(window).on('hashchange', ..) event listener , this one proved challenging and took a bit to hack on. Thanks to reading a lot of answers and trying different variations, finally figured out how to make it work in the following manner. Far as I can tell, it is looking stable so far.
In summary - there is the variable globalCurrentHash that should be set each time you load a view.
Then when $(window).on('hashchange', ..) event listener runs, it checks the following:
If location.hash has the same value, it means Going Forward
If location.hash has different value, it means Going Back
I realize using global vars isn't the most elegant solution, but doing things OO in JS seems tricky to me so far. Suggestions for improvement/refinement certainly appreciated
Set Up:
Define a global var :
var globalCurrentHash = null;
When calling .load() to update the DIV, update the global var as well :
function loadMenuSelection(hrefVal) {
$('#layout_main').load(nextView);
globalCurrentHash = hrefVal;
}
On page ready, set up the listener to check the global var to see if Back Button is being pressed:
$(document).ready(function(){
$(window).on('hashchange', function(){
console.log( 'location.hash: ' + location.hash );
console.log( 'globalCurrentHash: ' + globalCurrentHash );
if (location.hash == globalCurrentHash) {
console.log( 'Going fwd' );
}
else {
console.log( 'Going Back' );
loadMenuSelection(location.hash);
}
});
});
It's available in the HTML5 History API. The event is called 'popstate'
Disable the url button by following function
window.onload = function () {
if (typeof history.pushState === "function") {
history.pushState("jibberish", null, null);
window.onpopstate = function () {
history.pushState('newjibberish', null, null);
// Handle the back (or forward) buttons here
// Will NOT handle refresh, use onbeforeunload for this.
};
}
else {
var ignoreHashChange = true;
window.onhashchange = function () {
if (!ignoreHashChange) {
ignoreHashChange = true;
window.location.hash = Math.random();
// Detect and redirect change here
// Works in older FF and IE9
// * it does mess with your hash symbol (anchor?) pound sign
// delimiter on the end of the URL
}
else {
ignoreHashChange = false;
}
};
}
};
Hasan Badshah's answer worked for me, but the method is slated to be deprecated and may be problematic for others going forward. Following the MDN web docs on alternative methods, I landed here: PerformanceNavigationTiming.type
if (performance.getEntriesByType("navigation")[0].type === 'back_forward') {
// back or forward button functionality
}
This doesn't directly solve for back button over the forward button, but was good enough for what I needed. In the docs they detail the available event data that may be helpful with solving your specific needs:
function print_nav_timing_data() {
// Use getEntriesByType() to just get the "navigation" events
var perfEntries = performance.getEntriesByType("navigation");
for (var i=0; i < perfEntries.length; i++) {
console.log("= Navigation entry[" + i + "]");
var p = perfEntries[i];
// dom Properties
console.log("DOM content loaded = " + (p.domContentLoadedEventEnd -
p.domContentLoadedEventStart));
console.log("DOM complete = " + p.domComplete);
console.log("DOM interactive = " + p.interactive);
// document load and unload time
console.log("document load = " + (p.loadEventEnd - p.loadEventStart));
console.log("document unload = " + (p.unloadEventEnd -
p.unloadEventStart));
// other properties
console.log("type = " + p.type);
console.log("redirectCount = " + p.redirectCount);
}
}
According to the Docs at the time of this post it is still in a working draft state and is not supported in IE or Safari, but that may change by the time it is finished. Check the Docs for updates.
suppose you have a button:
<button onclick="backBtn();">Back...</button>
Here the code of the backBtn method:
function backBtn(){
parent.history.back();
return false;
}
I would like to implement a JavaScript code which states this:
if the page is loaded completely, refresh the page immediately, but only once.
I'm stuck at the "only once":
window.onload = function () {window.location.reload()}
this gives a loop without the "only once". jQuery is loaded if this helps.
I'd say use hash, like this:
window.onload = function() {
if(!window.location.hash) {
window.location = window.location + '#loaded';
window.location.reload();
}
}
When I meet this problem, I search to here but most of answers are trying to modify existing url. Here is another answer which works for me using localStorage.
<script type='text/javascript'>
(function()
{
if( window.localStorage )
{
if( !localStorage.getItem('firstLoad') )
{
localStorage['firstLoad'] = true;
window.location.reload();
}
else
localStorage.removeItem('firstLoad');
}
})();
</script>
<script type="text/javascript">
$(document).ready(function(){
//Check if the current URL contains '#'
if(document.URL.indexOf("#")==-1){
// Set the URL to whatever it was plus "#".
url = document.URL+"#";
location = "#";
//Reload the page
location.reload(true);
}
});
</script>
Due to the if condition the page will reload only once.I faced this problem too and when I search ,I found this nice solution.
This works for me fine.
Check this Link it contains a java-script code that you can use to refresh your page only once
http://www.hotscripts.com/forums/javascript/4460-how-do-i-have-page-automatically-refesh-only-once.html
There are more than one way to refresh your page:
solution1:
To refresh a page once each time it opens use:
<head>
<META HTTP-EQUIV="Pragma" CONTENT="no-cache">
<META HTTP-EQUIV="Expires" CONTENT="-1">
</head>
sollution2:
<script language=" JavaScript" >
<!--
function LoadOnce()
{
window.location.reload();
}
//-->
</script>
Then change your to say
<Body onLoad=" LoadOnce()" >
solution3:
response.setIntHeader("Refresh", 1);
But this solution will refresh the page more than one time depend on the time you specifying
I hope that will help you
<script>
function reloadIt() {
if (window.location.href.substr(-2) !== "?r") {
window.location = window.location.href + "?r";
}
}
setTimeout('reloadIt()', 1000)();
</script>
this works perfectly
Finally, I got a solution for reloading page once after two months research.
It works fine on my clientside JS project.
I wrote a function that below reloading page only once.
1) First getting browser domloading time
2) Get current timestamp
3) Browser domloading time + 10 seconds
4) If Browser domloading time + 10 seconds bigger than current now timestamp then page is able to be refreshed via "reloadPage();"
But if it's not bigger than 10 seconds that means page is just reloaded thus It will not be reloaded repeatedly.
5) Therefore if you call "reloadPage();" function in somewhere in your js file page will only be reloaded once.
Hope that helps somebody
// Reload Page Function //
function reloadPage() {
var currentDocumentTimestamp = new Date(performance.timing.domLoading).getTime();
// Current Time //
var now = Date.now();
// Total Process Lenght as Minutes //
var tenSec = 10 * 1000;
// End Time of Process //
var plusTenSec = currentDocumentTimestamp + tenSec;
if (now > plusTenSec) {
location.reload();
}
}
// You can call it in somewhere //
reloadPage();
i put this inside my head tags of the page i want a single reload on:
<?php if(!isset($_GET['mc'])) {
echo '<meta http-equiv="refresh" content= "0;URL=?mc=mobile" />';
} ?>
the value "mc" can be set to whatever you want, but both must match in the 2 lines. and the "=mobile" can be "=anythingyouwant" it just needs a value to stop the refresh.
Use window.localStorage... like this:
var refresh = window.localStorage.getItem('refresh');
console.log(refresh);
if (refresh===null){
window.location.reload();
window.localStorage.setItem('refresh', "1");
}
It works for me.
After </body> tag:
<script type="text/javascript">
if (location.href.indexOf('reload')==-1)
{
location.href=location.href+'?reload';
}
</script>
You can make one verable once = false then reload your page with if else like if once == false reload page an make once true.
You'd need to use either GET or POST information. GET would be simplest. Your JS would check the URL, if a certain param wasn't found, it wouldn't just refresh the page, but rather send the user to a "different" url, which would be the same URL but with the GET parameter in it.
For example:
http://example.com -->will refresh
http://example.com?refresh=no -->won't refresh
If you don't want the messy URL, then I'd include some PHP right at the beginning of the body that echos a hidden value that essentitally says whether the necessary POST param for not refreshing the page was included in the initial page request. Right after that, you'd include some JS to check that value and refresh the page WITH that POST information if necessary.
Try with this
var element = document.getElementById('position');
element.scrollIntoView(true);`
Please try with the code below
var windowWidth = $(window).width();
$(window).resize(function() {
if(windowWidth != $(window).width()){
location.reload();
return;
}
});
Here is another solution with setTimeout, not perfect, but it works:
It requires a parameter in the current url, so just image the current url looks like this:
www.google.com?time=1
The following code make the page reload just once:
// Reload Page Function //
// get the time parameter //
let parameter = new URLSearchParams(window.location.search);
let time = parameter.get("time");
console.log(time)//1
let timeId;
if (time == 1) {
// reload the page after 0 ms //
timeId = setTimeout(() => {
window.location.reload();//
}, 0);
// change the time parameter to 0 //
let currentUrl = new URL(window.location.href);
let param = new URLSearchParams(currentUrl.search);
param.set("time", 0);
// replace the time parameter in url to 0; now it is 0 not 1 //
window.history.replaceState({}, "", `${currentUrl.pathname}?${param}`);
// cancel the setTimeout function after 0 ms //
let currentTime = Date.now();
if (Date.now() - currentTime > 0) {
clearTimeout(timeId);
}
}
The accepted answer uses the least amount of code and is easy to understand. I just provided another solution to this.
Hope this helps others.
React Hook worked for me.
import { useEffect, useState } from 'react';
const [load, setLoad] = useState(false);
window.onload = function pageLoad() {
if (load) {
window.location.reload(true);
setLoad(false);
}
};
nothing work for me perfectly except this, -added to my JavaScript file-:
function LoadOnce() {
if (localStorage.getItem('executed') == 'false') {
window.location.reload()
localStorage.setItem('executed', true)
}
}
setTimeout(function () {
LoadOnce()
}, 100)
and in the previous page I wrote:
localStorage.setItem('executed', false)
I got the Answer from here and modified it.This is the perfect solution for me.
var refresh = window.localStorage.getItem('refresh');
console.log(refresh);
setTimeout(function() {
if (refresh===null){
window.location.reload();
window.localStorage.setItem('refresh', "1");
}
}, 1500); // 1500 milliseconds = 1.5 seconds
setTimeout(function() {
localStorage.removeItem('refresh')
}, 1700); // 1700 milliseconds = 1.7 seconds
var foo = true;
if (foo){
window.location.reload(true);
foo = false;
}
use this
<body onload = "if (location.search.length < 1){window.location.reload()}">
Use rel="external"
like below is the example
<li>Home</li>
I am trying to reload current page with different url hash, but it doesn't work as expected.
(Clarification how I want it to work: Reload the page and then scroll to the new hash.)
Approach #1:
window.location.hash = "#" + newhash;
Only scrolls to this anchor without reloading the page.
Approach #2:
window.location.hash = "#" + newhash;
window.location.reload(true);
Kinda works but it first scrolls to the anchor, then reloads the page, then scrolls to the anchor again.
Approach #3:
window.location.href = window.location.pathname + window.location.search + "&random=" + Math.round(Math.random()*100000) + "#" + newhash;
Works but I would rather not add random garbage to the url.
Is there a better solution?
Remove the anchor you're going to navigate to, then use approach #2? Since there's no anchor, setting the hash shouldn't scroll the page.
I had a JQuery function that fired on $(document).ready() which detected if there was a hash appended to the URL in my case, so I kept that function the same and then just used a force reload whenever a hash change was detected:
$(window).on('hashchange',function(){
window.location.reload(true);
});
Then my other function -
$(document).ready(function() {
var hash = window.location.hash;
if(hash) {
//DO STUFF I WANT TO DO WITH HASHES
}
});
In my case, it was fine for UX -- might not be good for others.
It should be expected that #foo will scroll to the anchor of the id, "foo". If you want to use approach #1 and have it reload, this approach might work.
if (Object.defineProperty && Object.getOwnPropertyDescriptor) { // ES5
var hashDescriptor = Object.getOwnPropertyDescriptor(location, "hash"),
hashSetter = hashDescriptor.set;
hashDescriptor.set = function (hash) {
hashSetter.call(location, hash);
location.reload(true);
};
Object.defineProperty(location, "hash", hashDescriptor);
} else if (location.__lookupSetter__ && location.__defineSetter__) { // JS
var hashSetter = location.__lookupSetter__("hash");
location.__defineSetter__("hash", function (hash) {
hashSetter.call(location, hash);
location.reload(true)
});
}
Another option is to remove the hash and store it in session storage to be retrieved on reload:
var newUrl = location.href + '#myHash';
var splitUrl = newUrl.split('#');
newUrl = splitUrl[0];
if (splitUrl[1]){
sessionStorage.savedHash = splitUrl[1];
}
location.href = newUrl;
and then on top of your page you can have the following code:
var savedHash = sessionStorage.savedHash;
if (savedHash){
delete sessionStorage.savedHash;
location.hash = savedHash;
}