Open specific links from a webpage with javascript? - javascript

I'm using Tampermonkey, and I can't seem to get jQuery to work on it so this has to be Javacript only.
I'm trying to get a script to open (in a new window) the link of an item on a webpage. I've got a list of items I need to open, here is an example of those items:
<a class="market_listings" href="http://blabla.com/item1">...</a>
<a class="market_listings" href="http://blabla.com/item2">...</a>
<a class="market_listings" href="http://blabla.com/item3">...</a>
etc.
As you can see, the item is defined by a class and an href. The class is not unique, but the href is.
I'm new to programming but this is my idea on how to open specifically those links from the page:
The script gets elements with class="market_listings",
just to narrow down the search of hrefs on the page.
The script looks if the href of those elements corresponds with
"http://blabla.com/item*"
The script opens a new window with that href.
I have pretty much 0 experience with coding, but this is how I'd start it, considering I only want to open items 1 and 3:
function gethrefandopenwindow() {
var items = document.getElementsByClassName('market_listings')
//don't know how to code from here
if (*a href of items corresponds to*: 'http://blabla.com/item1')
{
*open new window to href of item1*
}
if (*a href of items corresponds to*: 'http://blabla.com/item3')
{
*open new window to href of item3*
}
else {
*refresh the page and start over*
}
}
As I said, I have barely programming experience, so I don't know if this is possible, and if it is and you're willing to help, please explain it to me like I'm a TOTAL idiot/newbie. :)
The only other way I could think of is this one: Javascript getElement by href? ; Except I don't know how to apply it in my situation due to my noobiness (and how to open a specific href out of the elements).
Anyway, I hope you can help me,
Thank you!

It looks like you had the right idea. This function might get you moving in the right direction.
function OpenHrefsInNewWindow() {
//Get reference to your elements
var items = document.getElementsByClassName("market_listings");
for (var i = 0; i < items.length; i++) //Loop through your elements
{
//Verify that the href starts with http://blabla.com/item
if (items[i].href.indexOf("http://blabla.com/item") === 0)
{
//If it does, open that URL in a new window.
window.open(items[i].href, "_blank");
}
}
}
Another way to write it:
function OpenHrefsInNewWindow() {
//Get reference to your elements
var items = document.getElementsByClassName("market_listings");
var i = 0;
while(i < items.length) //Loop through your elements
{
//Verify that the href starts with http://blabla.com/item
if (items[i].href.indexOf("http://blabla.com/item") === 0)
{
//If it does, open that URL in a new window.
window.open(items[i].href, "_blank");
}
i++; //Increment i here.
}
}

Can retrive the url of link taking value of atribute and do ankthing later
Url = $(this).attr ('href')

Related

Activate iframe and change its contents

I am losing my marbles over this issue:
There's an iframe that i try to programmatically manipulate, but somehow this is only possible after i go into the developer console and click a parent node.
This is the best i can come up with:
var iframes = document.getElementsByTagName('iframe');
for (var i = 0; i < iframes.length; i++) {
if (iframes[i].parentNode.id == 'cke_355_contents') {
iframes[i].contentWindow.document.open();
iframes[i].contentWindow.document.write('<html><body>Hello World</body></html>');
iframes[i].contentWindow.document.close();
}
}
Even if i try to list all iframes on the page:
document.querySelectorAll('iframe').forEach((iframe)=> {
console.log(iframe.id, iframe.className, iframe.src)
});
i just get the first 2 results. But, when i click a parentnode in the console, it will only list the iframe i actually need.
Is there some way to find the correct iframe,"activate" it and manipulate it?

Javascript to Replace HREF with ONCLICK

I'm new to Javascript, and need some help with creating a script that adds 'onclick' to href links of a particular class on an HTML page, upon page load - using the link's href URL, without touching the inline code. The script would modify a regular link, from this
<a href="URL" class="XYZ">
to this:
<a href="#" onclick="location.href='URL';" class="XYZ">
The URL changes for each link but the class remains the same. Here is what I got so far, but I was wondering if it can be improved:
window.onload = function() {
// Saving all links with XYZ-class in a variable
let links = document.getElementsByClassName('XYZ');
// Iterating through the links, changing the onclick attribute
for(let i = 0; i < links.length; i++) {
// Saving the URL
let grabbedURL = links[i].getAttribute('href');
// Putting it in onclick
links[i].setAttribute('onclick', `location.href='${grabbedURL}'`);
// Replacing href with '#'
links[i].setAttribute('href', '#');
}
Here's an approach using a for...of loop; you can change that if you want:
// iterate through all results of a css selector
for (let link of document.querySelectorAll('a.XYZ')) {
// set onclick attribute as text
link.setAttribute('onclick', 'location.href = ' + JSON.stringify(link.href) + ';');
// set href attribute to empty anchor (#)
link.href = '#';
}
<body>
http://example.com/
<br>
http://foo.bar/
</body>
There could be more modern solutions to your problem using EventTarget.addEventListener(), but so far that's what you requested. If you have a question to this answer please write a comment under it.
And as you new to Stack Overflow: If you had a helpful answer for your question, you can mark it as accepted. Of cause only if you want. Doesn't have to be mine.
Placing this in your JS should do it:
const convert = () => {
const links = document.querySelectorAll("a");
for(let i = 0; i < links.length; i++){
let href = links[i].getAttribute("href");
let handleClick = () => {
console.log("the url is:",href)
window.location.href = href;
}
links[i].onclick = handleClick;
links[i].setAttribute("href","#");
}
}
convert();
I think you might be missing a larger point here. An anchor is designed for navigation, if you want to change the destination, don't set an onclick and then disable the href, just update the href to where you want to go.
And, to do this in the simplest way, use event delegation, where we leverage the fact that events bubble up from their origin to the document. We just create one event handler on a common ancestor of all the elements in question and handle the even there. When we do, we check to see if the event originated at an element that we care about using event.target and if it did, we act accordingly.
Here's an example:
let url = "https://example.com";
// Set an event listener on the document itself
document.addEventListener("click", function(event){
// Check to see if the event originated at an
// element we want to handle.
if(event.target.nodeName === "A" && event.target.classList.contains("XYZ")){
// Just update the href of the element
event.target.href = url;
}
});
<p>Click the links below. Only the XYZ links will take you to example.com</p>
XYZ
abc
qrs
XYZ
zzz
XYZ
aaa
XYZ
If I'm understanding your question, I think you want something like this:
function updateLink() {
var link = document.getElementById("linkId");
link.setAttribute('href', "http://google.com");
}
Then just add an 'id' to your link. Or get the class rather than the id.
document.getElementsByClassName('XYZ')[0].setAttribute("onclick","location.href='URL' ")
Try this..
For after page load effect add script at the very end of your body tag

Function to find string on page and click link next to it?

I'm wondering whether it is possible to devise a script which will search a webpage for a certain string of text, and then click the link in the element id directly to its right.
Is this possible. Maybe javascript, php?
Please help, and thanks to all that do. :)
#Four_lo
Thanks for your reply. I'm sorry, maybe it's because I'm pretty new to javascript, but I can't really understand anything on the page you suggested.
I put together some javascript which will search the page for an element id and click the link within there.
<html>
<head>
<script type="text/javascript">
function init(){
var linkPage = document.getElementById('linkid').href;
window.location.href = linkPage;
}
onload=init;
</script>
</head>
<body>
GO HERE
I WANT TO CLICK HERE!
</body>
</html>
So basically, I need to search the page for GO HERE. Then, once this is found, I need to click the link in id="thisone", if that makes sense.
The above code works, and clicks the link within the id specified. However, I'd like to find certain text within that id, then move onto the next id, and click the link within that id.
It is possible. It will probably take some finesse but here is where you should start to access String you need. I believe regular expressions will be a must as well.
http://dom.spec.whatwg.org/#processinginstruction
http://domparsing.spec.whatwg.org/
Slightly more complicated than it needs to be:
function performAfterLinkWithText(text, perform) {
// get all the links
var $links = document.getElementsByTagName('a');
// scan them for your text
for(var i in $links) {
if($links[i].innerHTML === text) {
var $next = $links[i] // ready for loop
, terminateAfter = 20 // don't repeat forever
;
// keep checking the adjacent element
// because newlines show up as #text
do {
$next = $next.nextSibling;
} while( !$next.href && terminateAfter-- > 0 );
// do your thing
perform($next.href, $next); // window.location.href = $next.href;
}
}
}
// test -- performAfterLinkWithText('GO HERE', function(url, link) { console.log(url, link); });
performAfterLinkWithText('GO HERE', function(url) { window.location.href = $next.href; });
Or with jQuery:
window.location.href = $('a:contains("GO HERE")').next().attr('href')

anchor jumping by using javascript

I have a question that will be found very often. The problem is that nowhere can be found an explicit solution.
I have two problems regarding anchors.
The main goal should be to get a nice clean url without any hashes in it while using anchors to jump on a page.
So the structure of the anchors is:
<ul>
<li>One</li>
<li>Two</li>
<li>Three</li>
</ul>
<div class="wrap">
<a name="one">text 1</a>
<a name="two">text 2</a>
<a name="three" class="box">text 3</a>
</div>
Okay, if you will click one of the links the url will automatically change to
www.domain.com/page#1
At the end this should be just:
www.domain.com/page
So far, so good. Now the second thing is, when you search the internet for that problem you will find javascript as a solution.
I have found this function:
function jumpto(anchor){
window.location.href = "#"+anchor;
}
and calling that function with:
<a onclick="jumpto('one');">One</a>
what will be the same like before. It will add the hash to the url. I also added
<a onclick="jumpto('one'); return false;">
without success. So if there is someone who could tell me how to solve this I really would appreciate.
Thanks a lot.
You can get the coordinate of the target element and set the scroll position to it. But this is so complicated.
Here is a lazier way to do that:
function jump(h){
var url = location.href; //Save down the URL without hash.
location.href = "#"+h; //Go to the target element.
history.replaceState(null,null,url); //Don't like hashes. Changing it back.
}
This uses replaceState to manipulate the url. If you also want support for IE, then you will have to do it the complicated way:
function jump(h){
var top = document.getElementById(h).offsetTop; //Getting Y of target element
window.scrollTo(0, top); //Go there directly or some transition
}​
Demo: http://jsfiddle.net/DerekL/rEpPA/
Another one w/ transition: http://jsfiddle.net/DerekL/x3edvp4t/
You can also use .scrollIntoView:
document.getElementById(h).scrollIntoView(); //Even IE6 supports this
(Well I lied. It's not complicated at all.)
I think it is much more simple solution:
window.location = (""+window.location).replace(/#[A-Za-z0-9_]*$/,'')+"#myAnchor"
This method does not reload the website, and sets the focus on the anchors which are needed for screen reader.
I don't have enough rep for a comment.
The getElementById() based method in the selected answer won't work if the anchor has name but not id set (which is not recommended, but does happen in the wild).
Something to bear in mind if you don't have control of the document markup (e.g. webextension).
The location based method in the selected answer can also be simplified with location.replace:
function jump(hash) { location.replace("#" + hash) }
Because when you do
window.location.href = "#"+anchor;
You load a new page, you can do:
One
<script>
function getPosition(element){
var e = document.getElementById(element);
var left = 0;
var top = 0;
do{
left += e.offsetLeft;
top += e.offsetTop;
}while(e = e.offsetParent);
return [left, top];
}
function jumpTo(id){
window.scrollTo(getPosition(id));
}
</script>
I have a button for a prompt that on click it opens the display dialogue and then I can write what I want to search and it goes to that location on the page. It uses javascript to answer the header.
On the .html file I have:
<button onclick="myFunction()">Load Prompt</button>
<span id="test100"><h4>Hello</h4></span>
On the .js file I have
function myFunction() {
var input = prompt("list or new or quit");
while(input !== "quit") {
if(input ==="test100") {
window.location.hash = 'test100';
return;
// else if(input.indexOf("test100") >= 0) {
// window.location.hash = 'test100';
// return;
// }
}
}
}
When I write test100 into the prompt, then it will go to where I have placed span id="test100" in the html file.
I use Google Chrome.
Note: This idea comes from linking on the same page using
Test link
which on click will send to the anchor. For it to work multiple times, from experience need to reload the page.
Credit to the people at stackoverflow (and possibly stackexchange, too) can't remember how I gathered all the bits and pieces. ☺
The first suggested solution of accepted solution did not work for me entirely. The main problem was when it was already jumped to hash, and hash already in url, jump did not happen again. I propose here, for the sake of completeness, somewhat more elaborate solution which works (tested in Chrome and FF). el is element with anchor tag.
el.addEventListener('click', function(ev) {
ev.preventDefault();
const href = ev.target.getAttribute('href');
const hashIndex = href.indexOf('#');
if (hashIndex !== -1) {
const hashPart = href.substring(hashIndex);
if (location.hash === hashPart) {
document.querySelector(hashPart).scrollIntoView();
}
else {
location.hash = hashPart;
}
}
})

Disabling a link tag using JavaScript on my printable page

I have a script that creates a printable page by copying the HTML across and then doing some manipulation, such as disabling the buttons on the page, on page load.
I also want to disable the links on the page. I don't really mind if they look like links still as long as they don't do anything, and don't give any JavaScript errors!
The anchor tag doesn't seem to have a disabled attribute...
Unfortunately, I can't use jQuery, so JavaScript only please!
Edit: I want to disable the links, buttons etc on the page so that when the 'printable page' opens in another window, the user cannot mess with it by clicking buttons or links. I want it to essentially be a 'frozen snapshot' of the page that they want to print.
Setting their href to # and overwriting the onclick event should do the trick.
var links = document.getElementsByTagName("A"), j;
for (j = 0;j < links.length; j += 1) {
links[j].href = '#';
links[j].onclick = function () {
return false;
};
}
Why can't you use jQuery? So much nicer...
$('a').each(function(){this.onclick=function(){return false}});
Anyway here is a normal javascript way. Smaller than above and you also don't need to modify the links... by defining the onclick function to return false it will not visit the href:
var anchors = document.getElementsByTagName("a");
for (i = 0; i < anchors.length; i++)
anchors[i].onclick = function(){return false};
There is also an array of links in the document object. While I've never tried, I believe you can set them too.
for (i=0;i<document.links.length;i+=1) {
document.links[i]=='#';
}

Categories