JQuery: Why won't the website open? - javascript

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.

Related

Is it possible to add a javascript for/while loop for location.reload();

My Wordpress site has conflicting plugins. So when I click a page in the menu, it get stuck but fixes when the page has been re-loaded.
My approach is to auto refresh the page (the menu link that has been clicked) so the page will properly load.
After searching for couple of days, I haven't found the exact way to do it.
I use
location.reload(true);
but it keeps reloading. I tried also
location.reload(true);
window.stop();
but it stops loading before it completes the page load to 100%.
So my question is, can we add a loop to stop the reload?
example…
after 2 reloads, the js code will stop
Hopefully someone can help me. Thanks!
Try this piece of JavaScript, it stores the reload count in LocalStorage:
if(typeof(localStorage.getItem('rlcount')) == 'undefined'){
localStorage.setItem('rlcount', 0);
}
if(localStorage.getItem('rlcount') < 2){
localStorage.setItem('rlcount', localStorage.getItem('rlcount') + 1);
window.location.reload();
}else{
localStorage.removeItem('rlcount');
}
However, you should note that reloading a page is not a good fix for your bug, you should find the root cause.
While I would encourage you to try to fix the root problem causing the behavior you described, you could do something like the following to reload the page twice:
window.onload = function() {
if (!window.location.hash) {
window.location = window.location + '#loadedOnce';
alert("Reloading first time...");
window.location.reload();
} else if (window.location.hash === "#loadedOnce") {
window.location = window.location.hash.replace("#loadedOnce", "#loadedTwice");
alert("Reloading second time...");
window.location.reload();
} else if (window.location.hash === "#loadedTwice") {
// Page reloaded twice, do whatever...
}
}
This makes use of a hash in the URL, so it does not require using the localStorage API (although that is a perfectly fine approach too if the browser supports it, and might work better if you already have hashes in the URL).
Thank you for taking time to answer my question guys…
I found a simple way (not a loop though). Not sure if this is ok but it's working when I added "return".
location.reload();
return;
When adding this command. it simply reloaded once.

Define a reference site for the history.back button

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

A Elements with HREF="#" causing page to reload on click

I have a few a elements which run functions via javascript and have a # set as the href however I have changed something recently that causes these to try and reload the page rather than do nothing and so breaks their functionality.
What can i look for that could cause this?
document.getElementById("link").onclick = function(){alert("do something javascript")};
<a id="link" href="#">Do Some JS</a>
Clicking this however reloads page and am unsure what i have done to cause this to reload the page.
I can't reproduce in the snippet, if i did i wouldn't be asking the question but something is causing these links to reload the page which is not expected behaviour.
So far i can only think or a quick and dirty fix:
$('a[href="#"]')).click(function() {
e.preventDefault();
});
I however would like to know what could be causing this issue to arise.
The problem
Ok i found it thanks for your help:
window.onpopstate = function(e){
if(e.state !== null) {
} else {
location.reload();
}
}
That will do it for sure.
I think it's so that as pages are heavily reliant on ajax there was no way to go back to where you had been.
I figured the easiest way was have the urls update on ajax changes so when i clicked back the url would change to last action and then cause page to reload correctly on pop state change.
My Quick Fix
I will change the code to:
window.onpopstate = function(e){
if(e.state !== null) {
} else {
if(window.location.href.substr(window.location.href.length - 1) != "#") {
location.reload();
}
}
}
This is normal behaviour of a tags if you don't want them to reload your page or scroll to top of your page you should remove href from your a tags. You can also stop them from reloading your page like this:
No reload
No reload
In your function you need to use e.preventDefault() or event.preventDefault(). So for example:
function clickMe(e) {
e.preventDefault();
}
As per the most recent comment, you need to pass in the event to the function so it looks like this:
$('a[href="#"]')).click(function(e) {
e.preventDefault();
});
Note that this is an approach I wouldn't recommend since it will block all links and could cause more problems than intended. You'll want to use a specific class to target your anchors.
try
<a onClick="callback();"></a>
just remove that href= "#"
It will not reload or refresh the browser
try javascript:void(0) instead #
eg.
Link
because without seeing some code we never know what cause this problem.

Page failing to redirect and clearing URL parameters

I have a webpage that makes a POST request to a PHP script. Depending on the result of the request, the onclick event for a button sets a redirect to one of two pages.
<button id="button" type="submit">Proceed</button>
...
$.post('script.php', {
key: value
}, function(result) {
if (result != null) {
document.getElementById("button").onclick = function() {
window.top.location.href = "https://example.com/page?otherkey=othervalue";
}
} else {
document.getElementById("button").onclick = function() {
window.top.location.href = "https://example.com/otherpage?otherkey=othervalue";
};
}
});
This works fine on desktop browsers, but on Safari on iOS (specifically tested on iOS 10.3.2) upon clicking the button, the page refreshes and doesn't redirect to the correct site. In addition, it clears any URL parameters that were previously there. So for example if the page with the button is example.com/page?key=value, the page will refresh and become example.com/page?#_=_. I've tried debugging and checking a Javascript console, but it doesn't say anything.
The redirect is a page in my own domain, though the page with the button is integrated into a Facebook app page, if that's relevant.
Also, if I construct the URL on my own and try to go to it normally, it loads fine. I don't know what could cause this, so I'm not sure if there's any other relevant information worth posting, but I can say more if necessary.
Safari does not deal well with return false being done in the function, and especially with no return at all. I would include a onsubmit="return function();" in the html element, which I'm guessing is a form. You also attach this to the submit() event listener via $('[the form ID]').submit(function(){ do something here; return false;});
I was right that I suppose I didn't supply enough detail, but it seems that because the button in question was inside a <form> tag and acting as a submit button, that was messing it up. To solve the issue, I removed the form (since I was not submitting any data anywhere, just using the button to redirect the page) and it solved the issue. Now it works on desktop and mobile browsers.

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

Categories