I have the following code that is executed on a button click:
location.replace(window.location.href.split('?')[0] + _new_urli);
My url looks like: https://mywebsite.com/website/?page=page1
For the sake of example we have:
Current behavior:
After location.replace() the current url stays in history and user can click back to it
Desired/intended behavior:
If successful the user will be forwarded. If they press back will not be able to visit the page i used location.replace on.
This is the described functionality on: http://www.w3schools.com/jsref/met_loc_replace.asp
You could probably use the historyof navigation.
Something like history.go(-2); should work.
If you want to modify url you can have a look at history.pushState(null, null, "newURL"); or in your case probably more history.replaceState().
The thing is the back button does not keep change so if your data is changed on page 3 you need an other way to pass it to the browser which could be the state object (the first parameter null) that can be set as {object: value,...}
This while probably interest you too. The thing is without knowing the behaviour of your site its difficult to help you find a proper solution. I hope this will inspire you.
Related
I have a 3 step signup process where each step is shown on the page using javascript without a page refresh. What I am trying to do now is add a back reference to what step the user was on so if they click the browser back button they will not lose all of their progress.
So for example, as the user navigates from Step 2 to Step 3 the URL stays at www.example.com. The user then clicks the browser back button. The URL should now be www.example.com?step-2.
I'm thinking that I will somehow need to use the History API to accomplish this but if I use window.history.pushState(null, null, 'www.example.com?step-2'), the current URL would be changed as well.
How would I accomplish adding to the history without changing the current URL?
If your objective is to not change the URL, but to still allow back and forth history state changes, your best bet would be to utilize the window's hashchange event listener. This would of course utilize hash references within the URL, but the base URL won't change:
function locationHashChanged() {
if (location.hash === '#step-2') {
// Do something here
}
}
window.onhashchange = locationHashChanged;
For further info on this, refer to official documentation:
https://developer.mozilla.org/en-US/docs/Web/API/Window/hashchange_event
We want to have a back button in our site
but history.back in javascript does not help us.
We need this function only run on the site and if the user comes from other site, clicking the return button on the previous site should not return.
In fact, we want a return button to run on our site only.
my code is
<i class="fas fa-arrow-left"></i><span class="btn-text">Back</span>
This only works for your own made back button and won't work with the browser back button
There is two ways to achieve that: a simple but not always reliable method and a complex one but always good.
1- The simple method
You use document.referrer and ensure the domain is yours before calling history.back().
2- The complex method
You could register a JavaScript function on page load to get the first URL the internaut land which you could store using history.pushState. Before calling the back function, you could ensure this is not that page. Though, this idea is not complete as the user could probably have landed on this page twice. i.e. Home->Product->Home. I'll let you search for further code that would let you counter this problem.
This code checks the history of back button of the browser on its click event:
$('#backbtn').click(function () {
if (document.referrer.includes(window.location.hostname)) {
window.history.back();
} else {
window.location.href = "/your/path";
}
});
I'm in the SeleniumIDE , but calling out to javascript.
Seems like this would be a fairly common scenario for others too.
I have a good test suite but the first thing it does is login.
I would like the suite to start off be making sure I am logged out and if not, logging me out.
I can tell if I am logged in by the presence of a 'Logout' hyperlink
But I only want to click on logout IF I am currently logged in, otherwise I want to do nothing, as trying to click on a non-existent element would raise an error if I am not already logged in)
So logically this is:
if ui element(logout link in my case) exists
click on logout link
else
do nothing
end
I am using the Selenium IDE and calling javascript - Given that I can't do if then in the basic seleniumIDE I was hoping I could do this in javascript itself.
something like:
store javascript{if ([a with text 'Logout' exists]) then click on it end;} id1
although instead of click on it [this], it would also be ok (though more brittle) if I just visited the url which is
http://my-apps-domain/users/sign_out
but I'm not sure of the exact syntax.
The relevant HTML is:
<li>Logout</li>
If it exists I would like to click on the a (or visit the url directly), otherwise nothing.
I would like to find a non-jquery solution if possible.
Update: I have found that even javascript{window.location.replace('http://google.com') } closes my seleniumIDE window and replaces it with google but doesn't affect the actual window where the tests themselves were running.
Triggering a click event in raw JavaScript can be tricky (check out this answer: https://stackoverflow.com/a/10339248/2386700)
However, if you can also use jQuery, that would simplify things. For example, if the logout button has an id like "logout" then you could do something like this:
var logoutButton = $('#logout');
if (logoutButton != null) {
logoutButton.click();
}
Since you don't have control over the HTML, I suggest referencing the link in another manner. The URL seems very reliable for that purpose:
var logoutLink = document.querySelector('a[href="/users/sign_out"]');
if(logoutLink != null) {
window.location.href = logoutLink.href;
}
You don't need to fire any kind of click event, because page navigation can easily be done with window.location.
UPDATE:
Another idea is to assign your button an id, then click it with selenium:
var logoutLink = document.querySelector('a[href="/users/sign_out"]');
if(logoutLink != null) {
logoutLink.setAttribute("id", "logoutLink");
}
In facebook, whenever you navigate to a different URL (in some situations), the URL changes but there is no feeling sensed as going to a different page.
For example: when we view pictures in facebook, and when we move to the next image the URL changes in the address bar
FROM >facebook.com/foo?bar=foobar&xxxx=
TO > >>facebook.com/foo?bar=boobar&xxxx=
and this is not hashed change also
like
FROM >facebook.com/xxxxx#xxx=xxxx
TO > >>facebook.com/xxxxx#xxx=yyyy
How is this possible seamlessly. I mean how is that only a container is modified on URL change. URL change is supposed to navigate to a different page which can contain cached information from previous page and THIS navigation by URL change can be seen obviously by browser's screen going blank for a moment.
If using an iFrame, how to implement this ?
I use somehting similar to this
try {
var stateObj = { foo: "bar" };
history.pushState(stateObj, "page", href);
loadPage(href);
}
catch(e) {
window.location.hash = "#!/"+href;
}
If it supports the HTML5 pushState them change URL, but if it doesn't then the fall back is the window hash.
wow. I just asked it few minutes ago ... use search next time ;)
Dynamic favicon when I'm proccessing ajax data
Modify the URL without reloading the page
There's a jQuery plugin called "address" that will watch for changes and call the function you give. I think it's just checking the URL every 100ms or so.
They issue an AJAX request for the data necessary to fulfil the "navigation", then tell the browser to "go to #xxx=yyy". Since such an anchor doesn't exist, the browser doesn't actually scroll down. However, it does record a new history entry, and also updates the URL so that if someone copy-pastes that URL, they will view the same object that the user is seeing, rather than just the original page.
Say I'm on a page called /example#myanchor1 where myanchor is an anchor in the page.
I'd like to link to /example#myanchor2, but force the page to reload while doing so.
The reason is that I run js to detect the anchor from the url at the page load.
The problem (normally expected behavior) here though, is that the browser just sends me to that specific anchor on the page without reloading the page.
How would I go about doing so? JS is OK.
I would suggest monitoring the anchor in the URL to avoid a reload, that's pretty much the point of using anchors for control-flow. But still here goes. I'd say the easiest way to force a reload using a simple anchor-link would be to use
where in place of $random insert a random number (assuming "dummy" is not interpreted server side). I'm sure there's a way to reload the page after setting the anchor, but it's probably more difficult then simply reacting to the anchor being set and do the stuff you need at that point.
Then again, if you reload the page this way, you can just put myanchor2 as a query parameter instead, and render your stuff server side.
Edit
Note that the link above will reload in all circumstances, if you only need to reload if you're not already on the page, you need to have the dummy variable be more predictable, like so
I would still recommend just monitoring the hash though.
Simple like that
#hardcore
an example
Another way to do that is to set the url, and use window.location.reload() to force the reload.
<a href="/example#myanchor2"
onclick="setTimeout(location.reload.bind(location), 1)">
</a>
Basically, the setTimeout delays the reload. As there is no return false in the onclick, the href is performed. The url is then changed by the href and only after that is the page reloaded.
No need for jQuery, and it is trivial.
My favorite solution, inspired by another answer is:
myanchor2
href link will not be followed so you can use your own preference, for example: "" or "#".
Even though I like the accepted answer I find this more elegant as it doesn't introduce a foreign parameter. And both #Qwerty's and #Stilltorik's answers were causing the hash to disappear after reload for me.
What's the point of using client-side JS if you're going to keep reloading the page all the time anyways? It might be a better idea to monitor the hash for changes even when the page is not reloading.
This page has a hash monitor library and a jQuery plugin to go with it.
If you really want to reload the page, why not use a query string (?foo) instead of a hash?
Another option that hasn't been mentioned yet is to bind event listeners (using jQuery for example) to the links that you care about (might be all of them, might not be) and get the listener to call whatever function you use.
Edit after comment
For example, you might have this code in your HTML:
example1
example2
example3
Then, you could add the following code to bind and respond to the links:
<script type="text/javascript">
$('a.myHash').click(function(e) {
e.preventDefault(); // Prevent the browser from handling the link normally, this stops the page from jumping around. Remove this line if you do want it to jump to the anchor as normal.
var linkHref = $(this).attr('href'); // Grab the URL from the link
if (linkHref.indexOf("#") != -1) { // Check that there's a # character
var hash = linkHref.substr(linkHref.indexOf("#") + 1); // Assign the hash to a variable (it will contain "myanchor1" etc
myFunctionThatDoesStuffWithTheHash(hash); // Call whatever javascript you use when the page loads and pass the hash to it
alert(hash); // Just for fun.
}
});
</script>
Note that I'm using the jQuery class selector to select the links I want to 'monitor', but you can use whatever selector you want.
Depending on how your existing code works, you may need to either modify how/what you pass to it (perhaps you will need to build a full URL including the new hash and pass that across - eg. http://www.example.com/example#myanchor1), or modify the existing code to accept what you pass to it from you new code.
Here's something like what I did (where "anc" isn't used for anything else):
And onload:
window.onload = function() {
var hash = document.location.hash.substring(1);
if (hash.length == 0) {
var anc = getURLParameter("anc");
if (anc != null) {
hash = document.location.hash = anc;
}
}
}
The getURLParameter function is from here
If you need to reload the page using the same anchor and expect the browser to return to that anchor, it won't. It will return to the user's previous scroll position.
Setting a random anchor, overwriting it and then reloading seems to fix it. Not entirely sure why.
var hash = window.location.hash;
window.location.hash = Math.random();
window.location.hash = hash;
window.location.reload();
Try this its help for me
<a onclick="location.href='link.html'">click me</a>
In your anchor tag instead of
click me
As suggested in another answer, monitoring the hash is also an option. I ended up solving it like this so it required minimal code changes. If I had asked the original question, I believe I would have loved to see this option fully explained.
The added benefit is that it allows for additional code for either of the situations (hash changed or page loaded). It also allows you to call the hash change code manually with a custom hash. I used jQuery because it makes the hash change detection a piece of cake.
Here goes!
Move all the code that fires when a hash is detected into a separate independent function:
function openHash(hash) {
// hashy code goes here
return false; // optional: prevents triggering href for onclick calls
}
Then detect your hash for both scenarios like so:
// page load
$(function () {
if(typeof location.hash != typeof undefined) {
// here you can add additional code to trigger only on page load
openHash(location.hash);
}
});
// hash change
$(window).on('hashchange', function() {
// here you can add additional code to trigger only on hash change
openHash(location.hash);
});
And you can also call the code manually now like
Magic
Hope this helps anyone!
Try this by adding simple question mark:
Going to Anchor2 with Refresh