selenium-webdriver npm detect successful link click - javascript

Is there a reliable way to detect a successful link click to an unknown page with selenium-webdriver npm?
I need to be able to test a simple page load on my site and check that an outbound link to an unknown page loads up ok. The site i am working on is a holiday letting site that displays a link to the hotels own page (so the contents of the target link will be completely unknown), i cannot find any way of reliably checking if the hotels website loads up or not using selenium.
Here is the test i have got thus far:
//1 load up the url
driver.get( testConfig.url + '/britain/england/cornwall/hotel88').then(function(){
//2 get current page html title
var title = driver.findElement(By.css('title'));
title.getInnerHtml().then(function(html) {
var controlTestTitle = html;
//3 now move onto the owners link
driver.findElement(By.css('.details-web')).click().then(function(){
driver.wait(function(){
return driver.isElementPresent(By.css("title"));
}, testConfig.timeout).then(function(){
var title = driver.findElement(By.css('title'));
title.getInnerHtml().then(function(html) {
//check that this title is not the same
if( html != controlTestTitle ){
if (callback) {
callback(callback);
}
} else {
throw 'the page title did not change when moving onto the owners website';
}
});
});
});
});
});
The above code is simply checking that the target page's html title is not the same as the original one.. but when the test runs i do not see the hotel's site actually loading up so i am not confident that the test is actually a success or not.
I did find this site trying to explain it, however the code is java which i do not know.. plus (as you can likely tell from the nature of this post) i am very new to selenium...

According to your comment, and your desire to use selenium for this task:
What you can do is, find at least 1 element on the page that would appear after clicking the link.
Once you click the link, simply validate that the one element you found, is present on the page. If not, then that means the page didn't load correctly.

Related

Generating a Youtube embed iframe from URL in a form for preview

So I am creating a form where people can input all sorts of data describing a recipe. One of those data types is a youtube video URL. I want to take the data the user puts into the URL box and generate an iframe with the video so that can preview and make sure it's the right one. This is the code I am using:
function makeVideoPreview(aTable, aTextBox)
{
var aVideo = document.createElement("iframe");
aVideo.setAttribute("width", "560");
aVideo.setAttribute("height", "315");
var theURL = aTextBox.value;
var idIndex = theURL.indexOf("v=") + 2;
var vidID = theURL.slice(idIndex, theURL.length );;
var embedLink = "https://www.youtube.com/embed/"+ vidID;
aVideo.setAttribute("src", embedLink);
aVideo.setAttribute('allowfullscreen', 'true');
aVideo.setAttribute('frameborder', "0");
aTable.appendChild(aVideo);
}
If I use the debugger and step through the code, the iframe gets placed in the right place, begins to load, and then I get a 405 method not allowed error and it reloads the entire page.
If I copy the generated iframe from the debugger and paste it into the html source, it works fine. What in the world is going on?
I'm not a web guy. I mostly do native iOS development, but I am making this as a resource so that the company I am making the app for can add recipe content. I'm sure it is something I just don't understand about the platform.
thanks.
I just found an answer! I think. Apparently every element “button” defaults to submit. I assumed that submit was a submit and button was an action less element unless given a specific onclick or similar function. Apparently one must set the button type to be button or it defaults to submit.

Detect which link was clicked with javascript that got user to specific page

Been searching on the web for a solution, but couldn't find anything, so maybe it's not possible, although I hope it still is.
What Im trying to do is detect the button (class or id) that was clicked when being redirected to another page on my site.
What I have is a portfolio page that contains a large amount of divs with different classes, so when someone clicks on a specific button on the homepage and gets redirected to the portfolio page, is it possible to detect on the portfolio page how the visitor got directed from. So detect which button got clicked.
no idea how to approach this, something maybe with if previous window.location last action find class or id.
Hopefully my question makes sense and someone can give me an idea if even possible.
I imagine it would rather be possible to do with php, but unfortunately server side languages are not an option in this case.
Thanks
Examples of methods you can use
add the information in the originating url - use location.search or location.hash depending on your choice of ? or #
Set a cookie (or use session/localStorage in modern browsers) in originating page and read it in the target page
Interrogate document.referrer (not always set)
You can't do it without either modifying the links (adding a query string or hash), or having code on the source pages (where the links are).
The former is pretty obvious: Just add a query string or hash (I'd use a hash) that identifies where the click came from, and look for the hash on the portfolio page. E.g., links:
Portfolio
Portfolio
and in the portfolio page:
var from = location.hash;
If you don't want to do that, and you can put code on those pages, it's easy: Add a click handler that sets information about the link in sessionStorage (very well-supported on modern browsers), and look for it in sessionStorage when you get to the portfolio page.
E.g.,:
$(document).on("click", "a", function(e) {
// Maybe check the link is going to portfolio, or refine the selector above
sessionStorage.setItem("linkFrom", this.className);
});
and then in the portfolio page:
var from = sessionstorage.getItem("linkFrom");
You can use window.localStorage to save the last id of the clicked element.
localStorage.setItem('last_clicked_id', id);
And then read it in the next page:
localStorage.last_clicked_id
Before running you should check for localStorage support:
if(typeof(Storage) !== "undefined") {
//localStorage code
} else {
//no localStorage support
}
this is how it works: the recent page or url is set on the URL parameters like a GET server request, but instead the client will receive it and parse it not the server. the recent page or url is on the "fromurl" parameter. on every page put this in (it's a javascript code):
function getURIparams(s) {
loc = window.location.href;
loc = loc.substring((loc.indexOf("?")+1));
loc = loc.split("&");
for (l = 0; l < loc.length; l++) {
lcc = loc[l].split("=");
if (lcc[0] == s) {
return lcc[1];
break;
}
}
}
next on every anchor link put this in href:
The Link to another page
after that, on every page execute this javascript:
from_url = getURIparams("fromurl");
the "from_url" variable will be the string variable of where the user clicked before it comes to that page.
if you are to lazy to put all those anchor one by one like this, do this work around but you need jquery for this. you dont need to put the parameter on the links for it to know where it comes from it will be automatically added by jquery.
$(document).on('click', 'a', function(e){
e.preventDefault();
window.location.href = e.target.href + "?fromurl=" + window.location.pathname;
});

Automatically Click Search Results

This may be a very rookie error I am making, but my situation is this. I have successfully made a script that when entered into a Google Chrome bookmark, it will bring up a prompt box upon the user clicking on the bookmark. From there, after they hit enter, it brings said user to a list of search results. What I want to do is put another piece of code in this same bookmark so that it automatically clicks on the first result on the search results page after it loads. Any ideas?
javascript: (function MCC() {
var feature = prompt('What is your search query?', '');
if (feature != null) {
window.open('https://www.google.com/#q=' + encodeURIComponent(feature));
window.onload = function MyClient() {
document.getElementById('mHSB').click();
}
}})();
I don't think there is a way to interact with a page inside of another window/frame. Your code snippet would run the function in the current window when the new window loaded.
If you are searching with google you could change the URL, something like
http://www.google.com/search?q=searchTerm&btnI
This should be the same as entering the search term and clicking Im feelin lucky (which should load the first result)
I got that link from
Is there a consistent way to link to Google "I Feel Lucky" result?
If you are searching on your own site/ a site where you can add code maybe a query-string switch would be a good idea.

Creating and structuring the index page

I have a test website www.lemonbrush.com is has the two menu items "Home" and "About".
When we click on the "About" menu, the About page is loaded dynamical, which is great, but when I type the About page's url directly http://www.lemonbrush.com/about.html into the address bar, my whole plan goes for six.
I need some guidance in how shall I structure and load the pages so that the whole header and navigation are included even when we use the direct URL in the address bar.
My skills are HTML and Javascript.
Please see the following screen shots.
When you're clicking the menu item you are updating the page with the data, but when you are going to the link directly you are just getting the data. one way around this is to have common elements for the page, ie. navigation menus, In a javascript file and then use a script tag with a link where you want it on the page.
so, since i thought it would be nice for my project, to have a usable browser history and bookmarkable subpages, i yesterday tried the approach from my comments of the OP.
step 1: change the anchors in your navigation bar to something like that:
home
about
needles to say, that they don't need to be inside the same parent element. those links could be anywhere.
step 2: remove the on click handler from your script, that reacts on the navigation bar clicks!
step 3: create a function, to listen to the onhashchange event. (this has to be done once, on the main html page)
//create a function for the onhashchange event
window.onhashchange = function()
{
//check if a location hash is used
if(window.location.hash != null)
{
//store current location hash in a variable
requestedPage = location.hash;
//remove the '#' from the location hash value
requestedPage = requestedPage.replace('#','');
//load content from subpage into your content frame
$('#contentFrame').load('./' + requestedPage + '.html', function( response, status, xhr )
{
//catch 'file not found' errors and load start page
if ( status == "error" ) {
$('#mainPanel').load('./start.html');
}
});
};
for your page, you have of course to adapt, use the correct selectors and the correct file names.
you then would call your page via www.mydomain.com, and every subdomain via www.mydomain.com/#subPage

jQuery code repeating problem

I have a piece of code in jQuery that I use to get the contents of an iFrame after you click a link and once the content is completed loading. It works, but I have a problem with it repeating - at least I think that is what it is doing, but I can't figure out why or how.
jQuery JS:
$(".pageSaveButton").bind("click",function(){
var theID = $(this).attr("rel");
$("#fileuploadframe").load(function(){
var response = $("#fileuploadframe").contents().find("html").html();
$.post("siteCreator.script.php",
{action:"savePage",html:response, id: theID},
function(data){
alert(data);
});
});
});
HTML Links ( one of many ):
<a href="templates/1000/files/index.php?pg=0&preview=false"
target="fileuploadframe" class="pageSaveButton" rel="0">Home</a>
So when you click the link, the page that is linked to is opened into the iframe, then the JS fires and waits for the content to finish loading and then grabs the iframe's content and sends it to a PHP script to save to a file. I have a problem where when you click multiple links in a row to save multiple files, the content of all the previous files are overwritten with the current file you have clicked on. I have checked my PHP and am pretty positive the fault is with the JS.
I have noticed that - since I have the PHP's return value alerted - that I get multiple alert boxes. If it is the first link you have clicked on since the main page loaded - then it is fine, but when you click on a second link you get the alert for each of the previous pages you clicked on in addition to the expected alert for the current page.
I hope I have explained well, please let me know if I need to explain better - I really need help resolving this. :) (and if you think the php script is relevant, I can post it - but it only prints out the $_POST variables to let me know what page info is being sent for debugging purposes.)
Thanks ahead of time,
Key
From jQuery .load() documentation I think you need to change your script to:
$(".pageSaveButton").bind("click",function(){
var theID = $(this).attr("rel");
var lnk = $(this).attr("href");//LINK TO LOAD
$("#fileuploadframe").load(lnk,
function(){
//EXECUTE AFTER LOAD IS COMPLETE
var response = $("#fileuploadframe").contents().find("html").html();
$.post("siteCreator.script.php",
{
action:"savePage",
html:response,
id: theID
},
function(data){alert(data);}
);
});
});
As for the multiple responses, you can use something like blockui to disable any further clicks till the .post call returns.
This is because the line
$("#fileuploadframe").load(function(){
Gets executed every time you press a link. Only add the loadhandler to the iframe on document.ready.
If a user has the ability via your UI to click multiple links that trigger this function, then you are going to run into this problem no matter what since you use the single iframe. I would suggest creating an iframe per save process, that why the rendering of one will not affect the other.

Categories

Resources