Add certain end to all the internal links on the page - javascript

I need some simple code on pure JavaScript (NOT jQuery!) that will add certain end to all the internal links on a page (i.e. to all the links that contain website domain in its href attribute), something like:
var pagelinks = document.getElementsByTagName('a');
for(var i in pagelinks) {
if(pagelinks.getAttribute('href').indexOf(document.domain) != -1) {
pagelinks[i].setAttribute('href',currenthref+'my_end');
}
}
!!! NOTE: it's not working script — it's only "something like" what I need
For example the internal links on a page are:
Showcase
Contacts
...
I need
Showcase
Contacts
...

If I understand your question correct this is what you want:
var domain = 'www.youtube.com';
var pagelinks = document.getElementsByTagName('a');
for (var i = 0; i < pagelinks.length; i++) {
var current = pagelinks[i].getAttribute('href');
if (current.indexOf(domain) !== -1) {
pagelinks[i].setAttribute('href', current + '?my_end');
}
}
Updated fiddle: https://jsfiddle.net/cm69qmnL/6/
You have to specify the domain you want to check the href attributes against and then run a loop which checks each anchor's href attribute, checks it against the specified domain and updated the href if the domain exists in current.

Related

Append query strings through links, buttons, menus etc

I have been using this javascript on my Wordpress site for sometime now and it has been working fine until a day or two ago, I did not change anything that would affect this. It still works fine on my test site so I cannot figure out why it stopped working. I am looking for any solution to the problem. Basically, agents are given a unique query string to give so when their customers visit the site, they will get commission. When a visitor goes from page to page or clicks the quote button (going to external portal), the query string passes page to page and to the external portal.
site.com/?group=agent123 - the script is loading. Firefox error is href is undefined. Chrome shows error regarding indexOf, line noted below fixed the error but did not make the script work... I am not a script writer so I cannot figure it out.
var index = window.location.href.indexOf('?')
if(index != -1){
var querystring = window.location.href.slice(index + 1)
var tagA = document.getElementsByTagName('a');
// this next line fixed the error hence allowing other
// broken scripts after this to work again but script does not work
// for appending the query strings...
if (href !== undefined)
for(var i = 0; i < tagA.length; i++){
var href = tagA[i].getAttribute('href');
href += (href.indexOf('?') != -1)? '&' : '?';
href += querystring;
tagA[i].setAttribute('href', href);
}
}
Just move if (href !== undefined) in for(var i = 0; i < tagA.length; i++){ after declaration of variable.
for(var i = 0; i < tagA.length; i++){
var href = tagA[i].getAttribute('href');
if (href !== undefined) {
href += (href.indexOf('?') != -1)? '&' : '?';
href += querystring;
tagA[i].setAttribute('href', href);
}
}
}
Best regards.

Iframe src attribute change with parameter

I’m trying to change the src attribute of an <iframe> depending if the iframe src has /?foo or not.
I had this solution:
<script>
jQuery(document).ready(function($) {
$('iframe[src*="?foo"]').each(function() {
$('#frame').attr('src', "http://www.example.com/page2");
});
});
</script>
<iframe id="frame" src=„www.example.com/page1/?foo"></iframe>
But my problem is that I have no access to the page, where the iframe is emded so I can't write this code into the <head> of the site.
I have access to both pages www.example.com/page1 and www.example.com/page2
I don’t know how I need to change the code to manipulate the src.. I am not sure if this is even possible, when I have no access to the page with the iframe
As seen in How to retrieve GET parameters from javascript? you can use the following code and call the function parseSecond("foo") to get the foo parameter on page1. You can find more information about this on the question page.
function parseSecond(val) {
var result = "Not found",
tmp = [];
var items = location.search.substr(1).split("&");
for (var index = 0; index < items.length; index++) {
tmp = items[index].split("=");
if (tmp[0] === val) result = decodeURIComponent(tmp[1]);
}
return result;
}
If you then want to redirect to page 2 you can write the following code to redirect the frame from page1 to page2 when the foo parameter has the value equal to bar.
if(parseSecond("foo")=="bar"){
window.location="www.example.com/page2";
}

Modify all links' href attribute using plain javascript only

I have an email template to send on a shipping notification that includes a shipping tracking number as below and I need to clear all the spaces from href using plain javascript:
<a class="press-bt" id="clearSpace" href="https://www.royalmail.com/track-your-item?trackNumber=JX12 0008 990 90GB">TRACK</a>
I can get it right using jQuery but not using Javascript
I am trying to do it this way:
window.onload = function() {
var str = document.getElementById("mylink");
document.write( str.replaceAll("\\s+","") );
});
Working code using jQuery:
$(document).ready(function() {
$('a').attr('href', function (_, val) {
return val.replace(/\s/g, '');
});
});
You should, if possible, remove the spaces server-side. I hope you understand no javascript will run in the emails you send.
// This prevents multiple `window.onload` conflict
window.addEventListener("load", clearLinks);
// This allows you to call the function even later if needed
function clearLinks() {
// Get list of all links in the page
var links = document.getElementsByTagName("a");
// Loop through links
for(var i=0,l=links.length; i<l; i++) {
// No need to use `getAttribute`, href is defined getter in all browsers
links[i].href = links[i].href.replace(/\s/g, "");
}
}
In modern browsers, you can replace the for loop with Array.prototype.forEach. This method can be normally called on arrays ([ ... ]), but the list returned by getElementsByTagName is not an array, so use this trick:
function clearLinks() {
var links = document.getElementsByTagName("a");
// Loop through links
Array.prototype.forEach.call(links, function(link) {
link.href = link.href.replace(/[cC]/g, "c");
});
}
Search for Function.prototype.call to learn more about calling functions on objects.
Target the element by its id, grab the href attribute, and set it again by removing the spaces.
var link = document.getElementById("mylink");
var href = link.getAttribute('href');
link.setAttribute('href', href.replace(/\s/g, ''));

Greasemonkey - Find link and add another link

We have an internal inventory at work that is web based. I am looking at add a link say under a link on the page. There is no ID, or classes for me to hook into. Each link at least that I want to add something below it, starts with NFD. I basically need to pull the link text (not the link itself the text that appears to the end user) and use that in my url to call a web address for remoting in.
var links = document.evaluate("//a[contains(#href, 'NFD')]", document, null,
XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null);
for (var i=0; i < links.snapshotLength; i++)
{
var thisLink = links.snapshotItem(i);
newElement = document.createElement("p");
newElement = innerHTML = ' Remote';
thisLink.parentNode.insertBefore(newElement, thisLink.nextSibling);
//thisLink.href += 'test.html';
}
Edit:
What I am looking for basically is I have a link NFDM0026 I am looking to add a link now below that using the text inside of the wickets so I want the NFDM0026 to make a custom link to call url using that. Like say a vnc viewer. The NFDM0026 changes of course to different names.
Here's how to do what you want (without jQuery; consider adding that wonderful library):
//--- Note that content search is case-sensitive.
var links = document.querySelectorAll ("a[href*='NFD']");
for (var J = links.length-1; J >= 0; --J) {
var thisLink = links[J];
var newElement = document.createElement ("p");
var newURL = thisLink.textContent.trim ();
newURL = 'http://YOUR_SITE/YOUR_URL/foo.asp?bar=' + newURL;
newElement.innerHTML = ' Remote';
InsertNodeAfter (newElement, thisLink);
}
function InsertNodeAfter (newElement, targetElement) {
var parent = targetElement.parentNode;
if (parent.lastChild == targetElement)
parent.appendChild (newElement);
else
parent.insertBefore (newElement, targetElement.nextSibling);
}

Make all hyperlinks in the site do nothing

I want to make a script that disables hyperlinks and instead fires a function when one is clicked.
should work as
<a onclick="talk('http://google.com)'></a>
Is there a way to know when the wants to redirect and instead run "talk()" or display an alert window?
var anchors = document.getElementsByTagName('a');
for (var a = 0; a < anchors.length; a++){
anchors[a].href = "javascript:talk('" + anchors[a].href + "');";
}
Use some discretion though...
This solution uses (DOM Level 0) event handling instead of touching the href directly.
(function () {
var anchors = document.getElementsByTagName('a'),
i = anchors.length;
while (i--) {
anchors[i].onclick = function () {
talk(this.href);
return false;
};
}
}());
Edit: The benefit of this approach is it's much simpler to put the href back when you want to. Given an anchor tAnchor, you merely need to unset the onclick attribute:
tAnchor.onclick = null

Categories

Resources