Define a reference site for the history.back button - javascript

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";
}
});

Related

JQuery: Why won't the website open?

I'm sort of new to JQuery, but I'm practicing everyday. My goal is to open the link after the buttons have been clicked but the link doesn't seem to be opening. I'm trying to open the link inside the if statement so everything happens accordingly.
window.setInterval(function(){
if ($('#add-remove-buttons').find('.button').length > 0) {
$('#size').val($('#size option').filter(function(ind, el) {
return $(el).text() === 'Large';
}).val());
$('#add-remove-buttons').find('.button').trigger('click');
setTimeout(function() {
window.location.replace('http://myweblink');
}, 900);
}
}, 100);
EDIT (STILL NEED HELP)
I've tried changing it but it doesn't load. I think it might be getting stuck in the 100ms loop. I put the function in a 100ms loop so it can detect if ($('#add-remove-buttons').find('.button').length > 0) I also just realized that after the user clicks the button, this html automatically appears:
<fieldset id="add-remove-buttons"><input class="button remove" name="commit" value="remove" type="submit">keep shopping</fieldset>
This means that the if statement : if ($('#add-remove-buttons').find('.button').length > 0) from my code, becomes false and the code for changing the URL doesn't run. Is there a way to detect the presence of the html code above like the if statement that became false? After I figure that out, I can put the window.location.href = "http://myweblink"; and then get it to work!
And in your code it is missing the complete web address.
Use
window.location.replace('http://myweblink.com');
Instead
window.location.replace('http://myweblink');
To redirect,jQuery is not necessary, and window.location.replace(...) will best simulate an HTTP redirect.
It is better than using window.location.href =, because replace() does not keep the originating page in the session history, meaning the user won't get stuck in a never-ending back-button fiasco. If you want to simulate someone clicking on a link, use location.href. If you want to simulate an HTTP redirect, use location.replace.
For example:
// similar behavior as an HTTP redirect
window.location.replace("http://stackoverflow.com");
// similar behavior as clicking on a link
window.location.href = "http://stackoverflow.com";
You can read the answer here.
Try
window.location.href = "http://your.wesite.com";
This will replace your address bar.
If you're using jQuery, just use $(location).attr('href',url);.
window.location.href seems to have inconstant behavior in some browsers, in fact, it flat out doesn't work in my version of Firefox.

remember most recent click

So I want to be able to have a different styling for a link after you go to the page it's clicked on. I have been using the following code:
$(document).ready(function(){
var url = document.URL;
function contains(search, find) {
return search.indexOf(find) !== -1;
};
$('#topbar a').each(function(){
var link = $(this).attr('href');
var answer = contains(link,url);
if(answer === true){
$(this).addClass('check');
}
else{
$(this).addClass('nocheck');
};
});
});
This goes through the links in my navigation bar and checks if it's on the same page as the link, and it works, but I can't use it in one specific case: Random.
I have a link that generates a random page from the pages I have, so it does not have a specified link as it links to a function to randomly generate the page (note: I cannot change the function or access information from it).
So how can I detect that the random link was clicked previously so i can give it the .check class
If i understand your question correctly, your function does not work for the randomlink because this has a href like http://mysite.com/random, but the server will actualy redirect you to a different page, like http://mysite.com/about-me, and therefore the url of the active page does not match the href of the random button, and it will not get the active state.
One could argue if you would want it to get the active state, cause clicking it again would not (likely) bring you to the same page, but that is besides the question.
I can see to ways to solve this.
server side:
In stead of redirecting to ie. http://mysite.com/about-me in the random function, you could also redirect to http://mysite.com/about-me?random. By adding this get variable, you should not change the behaviour of the link (unless you have some very strict controller, or that variable is actually used, but that is unlikely). You could then detect with javascript if that variable is present in the url, and then activate the random button.
Something like this:
$(document).ready(function(){
var url = document.URL;
// check for random
if (url.indexOf('?random') >= 0) {
$('#topbar a.random').addClass('check');
}
// check all other
$('#topbar a:not(.random)').each(function(){
if($(this).attr('href').indexOf(url) >= 0){
$(this).addClass('check');
}
else{
$(this).addClass('nocheck');
};
});
});
cookie:
If you do not have acces to the server side random controller, you could do it entirely with javascript, by the use of a cookie (the only way I know to make a variable persist trough page requests).
On click of the random button, you would first set a random cookie to true with javascript, before letting the actual link do it's thing. On entering the page, you could then do a similar check as in my previous option, but in stead of the url you check if the cookie is tre. If so, you change it to false (so on the next page request the random button will not be active again) and set the randombutton to active.
As I believe the first solution is to be preferred (cookies should only be used as a last resort, they are sent on every page request, which means extra data, and your user might have cookies disabled, or there might be laws against using cookies, so the function could not always work), I will not write the javascript yet. Feel free to ask if you prefer this solution and need further help however.

What's the javascript to only click a link if it exists?

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");
}

javascript history.back losses the search result

Page A:
$(document).ready(function () {
bindData();
});
function bindData() {
$('#searchbtn').bind('click', function () { SearchResult(); });
}
function SearchResult() {
ajax call...
}
Page A HTML:
<input type="button" id="searchbtn" />
Page B Details---> this page comes after selecting a specific search result from page A search list
Back<br />
Now when I go back to the Page A I can see my search criteria's as they were selected but the result Div is gone. What I am trying to do is I want the search list to stay when the Page comes back.
I think what I can do here is some how call the searchbtn click event again when the page comes back so the list will come-up again. Can anyone tell me how to fire the searchbtn click event only when the page comes back from Page B. or point me in the right way of doing this..
Thanks
The Browser Back button has long been problematic with AJAX. There are scripts, workarounds, and techniques out there (depending on the framework that you want to use).
Since it appears that you are using jQuery (based on your posted JavaScript syntax), here is a link to another Stackoverflow post regarding back button jQuery plugins.
history.back() will return you to the last URL visited, meaning that any ajax calls made during the user's visit will not be automatically repeated. Your browser may automatically restore your form selections, but the SearchResults() function is only called by a click event, not a selection event.
You can bind URLs to ajax states using a framework like sammy.js. That way, history.back() would take you to a URL associated with SearchResults().
function bindData() {
var chkinput1 = $("input:checkbox[name=x]:checked").length;
var chkinput2 = $("input:checkbox[name=y]:checked").length;
if (chkinput1 > 0 && chkinput2 > 0) {
SearchResult();
}
$('#searchbtn').bind('click', function () { SearchResult(); });
}
I know this is the worst way to achieve this result but I think instead of using any other plugins to add complexity we will go with this for now. If anyone else is looking for the same question let me tell you again this is not the best practice as on returning back to the history we are calling the search result again depending upon the cached input selection of checkboxes and generating the whole ajax call again to display the list. On the first request I am caching the list and setting sliding expiration so its not taking anytime to comeback and so everyone lives happily.

Javascript - Reload page after form submit with target="_blank"

I'm trying to achive the following:
On page A we have an access restricted Link to page B. The access restriction is handled on the server side in PHP.
When a user clicks on this link to page B we display a modal dialogue on page A (via javascript) with a form, having the link's href (B) as the action. (To give the user an immediate feedback. The fallback is to redirect him to a login form that redirects him to the site he wants to access.)
This system works quite well.
But now comes my question:
We have access restricted links that should be opened in a new window.
Now if I use target="_blank" on the form the user stays logged out on the page he came from (A), that is still open in the background.
Is there a way to reload the page (A, in the background) right after the form has been submitted to the new window (B)?
My first idea was to use window.location.reload(); in the submit handler on page A.
This didn't work in chrome and from what I understand could create a race condition.
Another idea would be to log the user in via an ajax call and open a new window through javascript. Is there a way to do this without having to deal with pop-up blockers?
I implemented the idea of lostsource (see below) with one slight addition.
As I need to reload only once, the timer of setInterval can be stopped if the cookie changed.
var ri=setInterval(function() {
if(oldCookie != document.cookie) {
// assuming a login happened, reload page
clearInterval(ri);
window.location.reload();
}
},1000); // check every second
I still love the idea. stackoverflow is awsome!
Assuming you're storing PHP session information inside a cookie, you might be able to monitor your document.cookie for changes.
Before submitting the form store the value of the current cookie and monitor it for changes with a timer:
form.onsubmit = function() {
var oldCookie = document.cookie;
var cookiePoll = setInterval(function() {
if(oldCookie != document.cookie) {
// stop polling
clearInterval(cookiePoll);
// assuming a login happened, reload page
window.location.reload();
}
},1000); // check every second
}
On the parent page, do you have any visual/functional changes because of the login? As in any new actions possible?
If not, then you dont have to do anything as you would be checking for login on every action from the parent page, you can check for permissions along with that.
If there are changes or additional functionalities, you can call a javascript function in the parent, say reloadMe, using window.opener.reloadMe()
Why not just a simple setTimeout
setTimeout(function(){ location.reload(); }, 1000);
It is a bit hacky, but seems appropriate for your situation.

Categories