casperjs, might need another click method? - javascript

I am new to casperjs, and as far as I have learned so far, there are only two click methods that can trigger a mouse action:
click() requires a selector
clickLabel() requires "label" between tags
The website I am dealing with right now has dynamic "tabs", by clicking each tab, a javascript submit is triggered, there is no "class", "id" or "label" associated with each tab, except for "pic" element:
<a href="javascript:submitTab('search6')" tabindex="6">
<img src="image6off.gif" name="imag6" height="6" hspace="0" vspace="0" border="0" onmouseover="nbGroup('over','imag6','image6on.gif','image6on.gif',1);" onmouseout="nbGroup('out');" onclick="nbGroup('down','group1','imag6','image6off.gif',1); submitTab('search6')" alt="New Search">
</a>
I tried to use clickLabel() but failed.
YES, I can use XPath, however the problem is the number of tabs is dynamic depending on the available information for each record, so in this case "new search" could be tab 6 for this record but tab 4 in another, tab 8 in yet another.
YES, I could try to write a "loop" to loop through all available tabs, potentially, however, if there is one method of click which combine the
waitForResource()
that would be great, since I can use the "image6on.gif" to tell the program which image or tab to click, apparently, for this website, I found out that each different javascript submit tab program is uniquely associated with one "image#on/off.gif"
I hope some contributor for casperjs can easily implement this method to deal this kind of situation.

Not entirely sure if this is what you want, but you can get the tab based on the tabindex attribute with:
casper.click("a[tabindex='6']");
Edit: Hack I threw together based on your comment below:
casper.thenEvaluate(function() {
var attr = document.querySelector('img[alt="New Search"]').parentNode.getAttribute('tabindex');
__utils__.click('a[tabindex="' + attr + '"]');
});
casper.thenEvaluate() allows you to execute javascript on the remote page.
__utils__ is injected into each page loaded as an extra set of functions that you can use.

I'm not a contributor to CasperJS. From my point of view the clickLabel function is already too much. I cannot remember that I actually used it, because most of the time there is something that prevents an exact string match.
You are right, it is a valid argument to add a new click function to CasperJS. In my opinion it is better to use the provided XPath capability to do that. You can even create the function for your use:
casper.clickByImg = function(imgRes){
var x = require('casper').selectXPath;
this.click(x("//a/img[contains(#href,"+imgRes+")]/.."));
return this;
};
See: minimal overhead.
You can even go this far as to match the image by a regular expression with more overhead.
casper.clickByImgRegexp = function(regexp){
var hrefs = this.getElementsAttribute("a > img", "href");
for(var i = 0; i < hrefs.length; i++) {
if (hrefs[i].match(regexp)) {
this.clickByImg(hrefs[i]);
break;
}
}
return this;
};

Related

Is there a to change the value of an element using JavaScript

I'm trying to change the value of an element on a third-party web page using a JavaScript Add-on to display a hyperlink
I already have the link on the page i would like to be able to click it
I think I'm on the right track using document.getElementById although I'm not sure how to then change the id into a "a href" and then how to pass it back into the value.
Sorry, this is a bit of a tricky situation so I'll try my best to explain it. On a third-party web-page which we use for our HR related tasks, there is a section titled "File Link" although this isn't a link. When you copy and paste the address into a browser it displays the file. What i am trying to do is create a hyperlink on the "File Link" section to remove the need to copy and paste the link. Because this is a third party website. We have access to the JavaScript on the website and need to change the address into a hyperlink. I'm not entirely sure this is possible.The element id is "__C_cb_file_link" and i would like to insert the link address into the element using a variable then add the link parameters into the variable then reinsert it into the element/value.
function linkIt() {
var intoLink = document.getElementById("__C_cb_file_link");
var hLink = "<a href="+intoLink+"</a>;
intoLink.value = hLink;
}
window.onload = linkIt();
<td><div class="sui-disabled" title="">m-files://view/37FF751C-A23F-4233-BD8B-243834E67731/0-46524?object=C46A7624-D24B-45F3-A301-5117EFC1F674</div>
<input type="hidden" name="__C_cb_file_link" id="__C_cb_file_link" value="m-files://view/37FF751C-A23F-4233-BD8B-243834E67731/0-46524?object=C46A7624-D24B-45F3-A301-5117EFC1F674"/></td></tr>
In below code first we read input value with new link (however we can read this value from other html tags), then we remove this element (and button) and add to parent element (of removed input) the new link
function linkIt() {
let intoLink = __C_cb_file_link.value;
let parent = __C_cb_file_link.parentNode;
__C_cb_file_link.remove();
btn.remove();
parent.innerHTML += `${intoLink}`;
}
<input id="__C_cb_file_link" value="https://example.com">
<button id="btn" onclick="linkIt()">Link It</button>
There are a number of issues with your code:
1) The code snippet in your question doesn't run because of a missing " at the end of the second line of the linkIt() function.
2) intoLink is a hidden field so anything you add to it will not be visible in the page
3) Even if point 2 were not true, setting the value of a form field will not cause HTML to appear on the page (at best you might get some plain text in a textbox).
4) "<a href="+intoLink+"</a>" doesn't work because intoLink is a complex object which represents the entire hidden field element (not just its value property). You can't convert a whole object into a string directly. You need to extract the value of the field.
A better way to do this is by creating a new element for the hyperlink and appending it to the page in a suitable place. Also I recommend not adding your event via onload - when written using this syntax only one onload event can exist in a page at once. Since you're amending another page which isn't under your control you don't want to disable any other load events which might be defined. Use addEventListener instead, which allows multiple handlers to be specified for the same event.
Demo:
function linkIt() {
var intoLink = document.getElementById("__C_cb_file_link");
var hLink = document.createElement("a");
hLink.setAttribute("href", intoLink.value);
hLink.innerHTML = "Click here";
intoLink.insertAdjacentElement('beforebegin', hLink);
}
window.addEventListener('load', linkIt);
<td>
<div class="sui-disabled" title="">m-files://view/37FF751C-A23F-4233-BD8B-243834E67731/0-46524?object=C46A7624-D24B-45F3-A301-5117EFC1F674</div>
<input type="hidden" name="__C_cb_file_link" id="__C_cb_file_link" value="m-files://view/37FF751C-A23F-4233-BD8B-243834E67731/0-46524?object=C46A7624-D24B-45F3-A301-5117EFC1F674" /></td>
</tr>
P.S. m-files:// is not a standard protocol in most browsers, unless some kind of extension has been installed, so even when you turn it into a hyperlink it may not work for everyone.
[UPDATE] I supose that your "__C_cb_file_link" was a paragraph so I get the previous text http://mylink.com and create a link with, is it what you want, right?
function linkIt() {
let fileLink = document.getElementById("__C_cb_file_link");
let hLink = fileLink.textContent;
fileLink.innerHTML = ""+hLink+"";
}
linkIt();
<div>
<p id="__C_cb_file_link">http://myLink.com</p>
</div>

How to add HTML code to a different HTML file using JavaScript or PHP

Alrighty, so I am trying to make a little page on my website that takes a few values and then when you click a button, it adds those values inside of a div on a different HTML page.
My code is:
<input type="text" name="URL"><br>
<input type="text" name="ImageURL"><br>
<input type="text" name="Title">
<button onclick="addCode()">Submit</button>
So for the addCode() function I want it so that it adds the values inside of a the item div on a different HTML file just like:
<div class="item">
<div class="animate-box">
<a href=URL><img src=ImageURL></a>
<div class="fh5co-desc"><a style="TEXT-DECORATION:none; COLOR:#818892; LINE-HEIGHT:20px;" href=URL>Title</a></div>
</div>
</div>
Thanks in advance.
What you are doing is technically impossible. without some sort of persistence, that is;
you cannot edit a page you aren't on. web browsing is a stateless technology.
if you meant you want to fill out those inputs then redirect on click and have those values available, there are a few different ways to do it:
1) Query String
write your code on the second page in a way that it accepts params from a query string in the url bar
function getURLParameter(name) {
return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search) || [null, ''])[1].replace(/\+/g, '%20')) || null;
}
var textDecoration = getUrlParameter('textdec'),
color = getUrlParameter('color'),
lineHeight = getUrlParameter('lnheight');
then you can send the request for the page as
http://page.com/page?textdec="someval"&color="somecolor"&lnheight="someheight"
however this will not work if you are not going directly to that page after your current one
2) localStorage
on your first page set the local storage values:
localStorage.setItem('lineHeight', 'someVal');
localStorage.setItem('color', 'someColor');
localStorage.setItem('textDecoration', 'someVal');
then on your second page retrieve the values
var lineHeight = localStorage.getItem('lineHeight'),
color = localStorage.getItem('color'),
textDecoration = localStorage.getItem('textDecoration');
3) serverSide persistence
this will vary MASSIVELY depending on how you your backend is structured
but the general gist is make a post request (ajax or otherwise) &
collect the data on the backend
then when you render the second page send the variables that were posted, either through interpolation or included as script variables
The only way to do this (without getting other technologies involved) is to use the localStorage, storage event. And, even with this, it will only work when the two pages are coming from the same domain and are open in different browser tabs (of the same browser) at the same time.
If those conditions are present, then modifying localStorage on one page will fire the storage event, which the other page can be set up to listen for. The other page can then respond to the event by pulling new values (that the first page wrote into localStorage) out and placing them anywhere on the second page that you like.
This is the kind of solution that you might encounter if you were on a travel site with more than one browser tab open. You may be looking at different flight options in different tabs. If one tab's code has an update that any/all other open tabs should know about, this technique does the trick.
Here's an example of how to set values into localStorage and use them. But, localStorage doesn't work here in the Stack Overflow snippet environment, so you can run the code here.
Once the values are in localStorage, you can pick them up from any other page that is being served from the same domain. So, the "getItem" code I'm showing here would really be placed on your "page2.html".
// Get DOM references:
var name = document.getElementById("name");
var color = document.getElementById("color");
var airspeed = document.getElementById("airspeed");
var btn = document.getElementById("btnGo");
// Set up button click event handler:
btn.addEventListener("click", function(){
// Get values and place in localStorage
localStorage.setItem("name", name.value);
localStorage.setItem("color", color.value);
localStorage.setItem("airspeed", airspeed.value);
// For demonstration, get values out of localStorage
console.log("What is your name? ", localStorage.getItem("name"));
console.log("What is your favorite color? ", localStorage.getItem("color"));
console.log("What is the airspeed of a laiden swallow? ", localStorage.getItem("airspeed"));
// If you wanted to redirect the user to the second page, now that the intial values
// have been set, you could just do:
location.href = "path to second page";
});
<div>What is your name?<input type="text" id="name"></div>
<div>What is your favorite color?<input type="text" id="color"></div>
<div>What is the airspeed of a laiden swallow?<input type="text" id="airspeed"></div>
<button id="btnGo">Go!</button>
If you're trying to edit the actual source code of the file, you'll need something like PHP. Otherwise, JS is just fine.
PHP Solution
You could use something like this:
<?php
$old = file_get_contents("some_page.html");
$content = explode("<span>",$old,2); // replace <span> w/ opening tag
$content = explode("</span>",$content[1],2); // replace </span> w/ closing tag
$data = "new content of element";
$new = str_replace($content[0],$data,$old);
?>
Updated JS Solution
You can't use my previous solution. Instead, you would have to create a function in the second HTML file that could be called from the first file, like this:
A script in file2.html:
function set(id,val){
$("#"+id).html(val); // jQuery
document.getElementById(id).innerHTML = val; // pure JS
}
A script in file1.html:
var win = window.open("http://example.com"); // open the window
win.set("some_id","Some content.") // the function that we set earlier
Note that this is reverted once the user closes or reloads the tab, and only applies to that user and that tab.

Read more opens 1st one all the time

I've a page with about 10 short articles.
Each of them as a "Read More" button which when pressed displays hidden text
The issues I have at the moment is when I press the "Read More" on any of the 10 button it shows the 1st articles hidden content and not the selected one.
I think I need to set a unique ID to each article.. and the read more button be linked to it.. But I don't know how to set it.
I looked at this but couldn't get it working how to give a div tag a unique id using javascript
var WidgetContentHideDisplay = {
init:function() {
if ($('#content-display-hide').size() == 0) return;
$('.triggerable').click(function(e){
var element_id = $(this).attr('rel');
var element = $('#'+element_id);
element.toggle();
if (element.is(':visible')) {
$('.readmore').hide();
} else {
$('.readmore').show();
}
return false;
});
}
}
var div = documentElemnt("div");
div.id = "div_" + new Date().gettime().toString;
$(document).ready(function(){ WidgetContentHideDisplay.init(); });
OP Edit: Sorry, the original code wasn't in caps. I kept getting errors when trying to post, so I copied the code into Dreamweaver and it made it all caps for some reason.
Instead of selecting the element to toggle with an ID (i.e. $('#'+ELEMENT_ID)) you could setup a class for your item and use the class selection (e.g. $('.DETAILED-ARTICLE)') to select the child (or the brother, etc. depending how you built the HTML page).
In theory each ID should point to a single element but each class can be put to as many elements as you want.
If you're getting errors, read the errors and see what they are. Off of a quick read of your code, here are a couple things I noticed that will probably cause issues:
"documentElemnt" is misspelled, which will render it useless. Also, documentElement is a read-only property, not a function like you're using it.
toString is a function, not a property, without the parentheses (.toString()) it isn't going to function like you want it to.
Run the code, look at the errors in the console, and fix them. That's where you start.

HTML 5 pattern attribute

Is there a way in <select> list, for example, to make onClick activate a JavaScript function that will show the title of the element just as pattern in HTML 5 does?
I want to do that when you click on the <select>, it will activate a JavaScript function that under some condition (doesn’t matter—some if expression) will show a sentence (that I wrote) in a bubble like place (the place that the pattern shows the title when something isn’t according to the pattern (pattern in HTML5)).
You can set a custom validity error on a select element by calling the setCustomValidity method, which is part of the constraint validation API in HTML5 CR. This should cause an error to be reported, upon an attempt at submitting the form, in a manner similar to reporting pattern mismatches. Example:
<select onclick="this.setCustomValidity('Error in selection');
title="Select a good option">
(In practice, you would probably not want to use onclick but onchange. But the question specifically mentions onClick.)
There are problems, though. This only sets an error condition and makes the element match the :invalid selector, so some error indicator may happen, but the error message is displayed only when the form data is being validated due to clicking on a submit button or something similar. In theory, you could use the reportValidity method to have the error shown immediately, but browsers don’t support it yet.
On Firefox, the width of the “bubble” is limited by the width of the select element and may become badly truncated if the longest option text is short. There is a simple CSS cure to that (though with a possible impact on the select menu appearance of course).
select { min-width: 150px }
You might also consider the following alternative, which does not affect the select element appearance in the normal state but may cause it to become wider when you set the custom error:
select:invalid { min-width: 150px }
There is also the problem that Firefox does not include the title attribute value in the bubble. A possible workaround (which may or may not be feasible, depending on context) is to omit the title attribute and include all the text needed into the argument that you pass to setCustomValidity.
A possible use case that I can imagine is a form with a select menu such that some options there are not allowed depending on the user’s previous choices. Then you could have
<select onchange="if(notAllowed(this)) setCustomValidity('Selection not allowed')" ...>
where notAllowed() is a suitable testing function that you define. However, it is probably better usability to either remove or disable options in a select as soon as some user’s choices make them disallowed. Admittedly, it might mean more coding work (especially since you would need to undo that if the user changes the other data so that the options should become allowed again).
In my opinion Jukka's solution is superior however, its fairly trivial to do something approaching what you're asking for in JavaScript. I've created a rudimentary script and example jsFiddle which should be enough to get you going.
var SelectBoxTip = {
init : function(){
SelectBoxTip.createTip();
SelectBoxTip.addListeners();
},
addListeners : function(){
var selects = document.getElementsByTagName("select");
for (var i = 0; i < selects.length; i++){
var zis = selects[i];
if(zis.getAttribute('title')){//only if it has a title
zis.addEventListener("focus", SelectBoxTip.showTip, false);
zis.addEventListener("blur", SelectBoxTip.hideTip, false);
}
}
},
createTip : function(){
tip = document.createElement("div");
tip.id = "tip";
tip.style.position = "absolute";
tip.style.bottom = "100%";
tip.style.left = "0";
tip.style.backgroundColor = "yellow";
document.body.appendChild(tip);
},
showTip : function(e){
this.parentNode.appendChild(tip);
tip.innerHTML=this.title;
tip.style.display="block";
},
hideTip : function(e){
tip.style.display="none";
}
};
SelectBoxTip.init();

How do I make this link work in javascript

Ok basically I have this javascript file http://assets.revback.com/scripts/share1.js that basically adds a bunch of share buttons via javascript.
What I want to do, is change the twitter image link to use an url shortener:
so instead of:
<a href=\"http:\/\/twitter.com\/home?status=Interesting Post:(UURRLL)\" title=\"Click to share this page on Twitter\"><img src=\"http:\/\/assets.revback.com\/scripts\/images\/twitter.png\" border=\"0\"\/><\/a>
I want to use
<a href="#" onClick="window.location='http://ko.ly?action=shorten&uri=' + window.location + '&dest=twitter.com/?status=Reading ';"><img src=http://assets.revback.com/scripts/images/twitter.png"><\/a>
but I need that bottom one, to be written with javascript friendly syntax. i.e. like in the top one, instead of http://, you have http://
Lose the onclick. There is no benefit to it whatsoever, since it just acts like a normal link (except much more broken). Now you don't have to worry about escaping JavaScript inside JavaScript and the consequent \\\\\\\\ madness.
var buttonhtml= (
'<a href="http://ko.ly?action=shorten&uri='+encodeURIComponent(location.href)+'&dest=twitter.com/?status=Reading">'+
'<img src=http://assets.revback.com/scripts/images/twitter.png">'+
'</a>'
);
(Note that the encodeURIComponent, which is essential to correctly inserting your current URL into another URL without breaking, is also protecting you from HTML-injection, since < and & characters get %-encoded. Without that safeguard, any page that includes your script has cross-site-scripting vulnerabilities.)
Better still, lose the HTML string-slinging altogether and use DOM methods to create your content. Then you don't need to worry about & and other HTML escapes, and you don't have to hack your HTML together with crude, unreliable string replacing. You seem to be using jQuery, so:
var link= $('<a>', {href:'http://ko.ly?action=shorten&uri='+encodeURIComponent(location.href)+'&dest=twitter.com/?status=Reading'});
link.append('<img>', {src: 'http://assets.revback.com/scripts/images/twitter.png'});
link.appendTo(mydiv);
ETA: I'd replace the whole markuppy mess with a loop and the data broken out into a lookup. ie. something like:
(function() {
var u= encodeURIComponent(location.href);
var t= encodeURIComponent(document.title);
var services= {
Facebook: 'http://www.facebook.com/sharer.php?u='+u,
Twitter: 'http://ko.ly?action=shorten&uri='+u+'&dest=twitter.com/?status=Reading',
StumbleUpon: 'http://www.stumbleupon.com\/submit?url='+u+'&title='+t,
// several more
};
var share= $('<div class="ea_share"><h4>Share this with others!</h4></div>');
for (var s in services) {
share.append($('<a>').attr('href', services[s]).attr('title', 'Click to share this on '+s).append(
$('<img>').attr('src', 'http://assets.styleguidence.com/scripts/images/'+s.toLowerCase()+'.png')
));
}
$('#question .vt').append(share);
})();
Try this
<a href="#" onClick="window.location='http://site.com?action=shorten&uri='+
window.location + '&dest=twitter.com/?status=Reading;'">tweet this</a>
<a href="#" onClick="window.location='http://site.com?action=shorten&uri=' + window.location.href + '&dest=twitter.com/?status=Reading ';return false;">tweet this
Change the href of the link in the onclick attribute:
tweet this
The default action (going to the page designated by the href attribute) will always still be executed unless the event handler onclick receives a return value of false. So, changing the href before it happens will cause it to go to the page you want it to as long as you don't return false.

Categories