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");
}
Related
I'm working on a web application which is a traditional aspx (asp.net) web forms app but has had some angular 6 apps incorporated into it.
I've been tasked with fixing a bug that causes the browser to refresh when clicking on an anchor element with a href="#".
I'm not sure what's causing the whole page to reload.
Strangely when I open dev tools in Chrome, choose the network tab and select disable cache the page only refreshes the first time I click a link and any other subsequent clicks work fine. This might be to do with the fact that after the first time I click it the browser url now contains the # at the end of it.
I know this seems a bit random but I wondered whether anyone had any theories on what may cause the reload in the first place.
It's hard to tell what could be causing this without seeing any code. The most common solution I've used when I get this behavior is a prevent default. You can do something like
<a href="#" (click)="$event.preventDefault()">
Or if you already have a click event then pass in $event as a parameter to your function then preventDefault in the function you are calling. This would look like:
Html
<a href="#" (click)="someFunc($event)">
and in your ts:
someFunc(event) {
event.preventDefault();
// rest of your code here
}
This answer is related to the question and it's the first one that comes up in Google so I hope this is useful.
I have some external web components that use regular anchor tags with hrefs that point to routes in my angular app. Clicking the href causes a full page reload. This is because I'm not using routerLink - but, in my case, I can't.
So, my work around is:
#HostListener('window:click', ['$event'])
onClick(e: any) {
const path = e.composedPath() as Array<any>;
const firstAnchor = path.find(p => p.tagName.toLowerCase() === 'a');
if (firstAnchor && !firstAnchor.hasAttribute('routerlink')) {
const href = firstAnchor.getAttribute('href');
this.router.navigateByUrl(href);
e.preventDefault();
}
}
Depending on your application, you might need to make some other checks e.g. is the target _blank, is it an external url etc.
change your a tag code as below
A Tag
this will invoke yourClickEvent(); without page reload
check the stackblitz here stackblitz
If you don't want to reload the page use $event.preventDefault()
<a href="#" (click)="$event.preventDefault()">
Try using debug tools to select the element, then click Event Listeners and then the Click event to see what is listening. Perhaps you can track it down that way.
You could also simply paste this into the console to trigger a break, and then click any of the offending elements:
['unload', 'beforeunload'].forEach(function (evName) {
window.addEventListener(evName, function () {
debugger; // Chance to check everything right before the redirect occurs
});
});
source: Break when window.location changes?
As you are using angular routes, try to use this notation:
<a [routerLink]="['./']" fragment="Test">
As explain by this comment: https://stackoverflow.com/a/38159597/4916355
use href="javascript:void(0);"
The reason you’d want to do this with the href of a link is that normally, a javascript: URL will redirect the browser to a plain text version of the result of evaluating that JavaScript. But if the result is undefined, then the browser stays on the same page. void(0) is just a short and simple script that evaluates to undefined.
Use [routerLink] instead of using href = "", and use click event to call your calling method in the typescript file.
ex:
// downloading the file based on file name
<a [routerLink]="'file://' + 'path'" (click)="downloadFile(templateDocument.fileName)">{{downloadDocuments.fileName}}</a>
Since you have mentioned the web app is asp.net webforms, can you please let us know
Whether the link is asp.net hyperlink control. If so,
AutoEventWireUp could cause the link to be automatically submitted:
Please have a look at this link
If you do have asp.net server controls on the page, then you could disable by setting
#Page AutoEventWireup="false"
For the entire project, this can be disabled by setting in web.config:
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";
}
});
<script type="text/javascript">
confirm("Delete user?.");
window.location.href = "users.php";
</script>
$qqq = mysql_query("DELETE from users WHERE panelistname='$theuser'") or die(mysql_error())
considering the code above, (inside a php file, so no worries with certain syntax errors you might notice) the problem here is that when click cancel on the confirm() dialog box that will show up. the delete action still executes. This question might be considered a double since, yeah, I found some questions relevant to this one but I just can't fixed this one myself.
the one I found codes it something like this:
"if (confirm('Are you...?')) commentDelete(1); return false"
I can't find a way to solve this problem, I don't know which part should I insert the SQL command(delete) in this format. Please someone show me how to do this right. :) thanks!
EDIT: I just saw that Nick Zuber posted a similar answer around 1 minute before I posted mine (actually, while I was writing it :P)
I don't clearly understand what you are trying to do.
You want to show the user a confirm window, and if they click Yes, delete some entry in the database, and if they click No, redirect them to the page 'users.php' ?
If it's what you want to do, then you can't do it like this. You can't use JS conditions with PHP. The PHP code is executed server-side (in the server), whereas the JS code is executed client-side (in the browser). What you would need is to do something like this:
warning: don't use this code, it's unsecure and shouldn't ever be used in a real app, it's just to show you how the whole thing works
(IN USERS.PHP)
if(isset($_GET['delete_dat_user']))
{
$qqq = mysql_query("DELETE from users WHERE panelistname='" . $_GET['delete_dat_user'] . "'") or die(mysql_error());
}
(IN THE WEBPAGE)
if(confirm('u serious u want to delete the user'))
{
window.location = 'users.php?delete_dat_user=theUserName';
}
else
{
nope
}
When your page loads, the PHP on your page will automatically execute, regardless of your JavaScript. Instead, try to prompt the user if they want to delete the account and if they click yes redirect them to a page that has your PHP query.
Also, the confirm function returns a boolean value depending on which option is clicked by the user. Try putting it in an if statement:
if(confirm("Delete user?.")){
window.location.href = "delete_user_page.php";
}else{
// cancel was clicked
}
So I recently started working on Greasemonkey scripts without much prior experience in JavaScript. It was going fine until I hit this roadbloack.
I'm writing a script for a page that has a small table of information. If a link at the bottom is clicked, the table expands fully in the page to display all information. I need to call a function in Greasemonkey when this happens, however, the link doesn't appear to have an ID or anything I can actually reference to watch it. It's simply this:
When it's clicked, the table expands and it then shows as true. I initially used the following to expand the table upon loading the page, but that broke several things:
window.location.href = ('javascript: expandFullTable(false)');
I've attempted using "click", "onclick", and even "mouseover" to have Greasemonkey detect when it's pressed but nothing seems to work. From what I can tell it's simply a link that calls a function, but after some significant searching I wasn't able to find out anything about how to reference it in my script. I'm sure it's incredibly simple, but it's frustrated me to no end.
You can hijack the function like this:
var oldExpandFullTable = unsafeWindow.expandFullTable;
unsafeWindow.expandFullTable = function() {
// Do something
alert("You clicked on that thing!");
// Call the original function
oldExpandFullTable.apply(this, arguments);
};
But since you tagged this jquery this should let you retrieve the link:
var link = $("a[href^=\"javascript: expandFullTable\"]);
It should work if jQuery is injected into your script with #require. If it's already in the page, you can add this before to access it: var $ = unsafeWindow.jQuery;.
And by the way, perhaps you should learn more about unsafeWindow to avoid security holes.
I'm stuck modifying someone else's source code, and unfortunately it's very strongly NOT documented.
I'm trying to figure out which function is called when I press a button as part of an effort to trace the current bug to it's source, and I"m having no luck. From what I can tell, the function is dynamically added to the button after it's generated. As a result, there's no onlick="" for me to examine, and I can't find anything else in my debug panel that helps.
While I prefer Chrome, I'm more than willing to boot up in a different browser if I have to.
In Chrome, type the following in your URL bar after the page has been fully loaded (don't forget to change the button class):
var b = document.getElementsByClassName("ButtonClass"); alert(b[0].onclick);
or you can try (make the appropriate changes for the correct button id):
var b = document.getElementById("ButtonID"); alert(b.onclick);
This should alert the function name/code snippet in a message box.
After having the function name or the code snippet you just gotta perform a seach through the .js files for the snippet/function name.
Hope it helps!
Open page with your browser's JavaScript debugger open
Click "Break all" or equivalent
Click button you wish to investigate (may require some finesse if mouseovering page elements causes events to be fired. If timeouts or intervals occur in the page, they may get in the way, too.)
Inspect the buttons markup and look at its class / id. Use that class or id and search the JavaScript, it's quite likely that the previous developer has done something like
document.getElementById('someId').onclick = someFunction...;
or
document.getElementById('someId').addEventListener("click", doSomething, false);
You can add a trace variable to each function. Use console.log() to view the trace results.
Like so:
function blah(trace) {
console.log('blah called from: '+trace);
}
(to view the results, you have to open the developer console)