Append query strings through links, buttons, menus etc - javascript

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.

Related

How to open all offsite links in a new window except for specific href?

On my site, I have some links that are built dynamically with JS. Not all of them contain an href value, so I add an href value dynamically. I use javascript:; as that value.
Now, I need to be able to open all links not on my host in a new window. Obviously, javascript:; is not my host, so any link with that in the href attribute will open in a new window.
In the snippet below, I'm trying to prevent that from happening, but I'm not getting the result I desire.
How do I push all offsite links to a new tab, except for one that I specify?
document.querySelectorAll("a:not(a[href])").forEach(element => {
element.setAttribute("href", "javascript:;")
});
var all_links = document.querySelectorAll('a');
for (var i = 0; i < all_links.length; i++) {
var a = all_links[i];
if (a.hostname != location.hostname || a.getAttribute("href") !== 'javascript:;') {
a.rel = 'noopener';
a.target = '_blank';
}
}
Yahoo!
<hr>
<a>something else</a>
Looks like this was the best solution...
If you inspect each link, you'll see that the external link has _blank, the internal link has _self, and the one with href="javascript:;" has _self.
document.querySelectorAll("a:not(a[href])").forEach(element => {
element.setAttribute("href", "javascript:;")
});
let all_links = document.querySelectorAll('a');
for (var i = 0; i < all_links.length; i++) {
let anchors = all_links[i];
if (anchors.getAttribute('href') == 'javascript:;' || anchors.hostname == location.hostname) {
anchors.target = "_self";
} else {
anchors.target = "_blank";
}
}
External Link (Yahoo!)
<hr>
Change the font and the line spacing of a style (SO Question)
<hr>
<a>anchor without href (Goes nowhere)</a>

How to redirect or iframe id content?

My code right now is currently this.
As you can see, it generates 2 random strings into places into a link containing both letters and numbers. But how can I force it to open or redirect to that newly generated link? Or even perhaps iFrame it?
Since right now, it just simply writes it out how the link will look after being generated.
By the way, what I am looking for is also here:
"
How to change part of an iFrame’s URL to a random string?
"
I got this far after seeing that.
function randString(x) {
var s = "";
while (s.length < x && x > 0) {
var r = Math.random();
s += (r < 0.1 ? Math.floor(r * 100) : String.fromCharCode(Math.floor(r * 26) + (r > 0.5 ? 97 : 65)));
}
return s;
}
document.getElementById("doo").innerHTML = randString(4);
The above is my JavaScript code found on the JSFiddle which I'm using for generating a part of the link.
Super simple stuff.. For now, you're just putting your generated link string into a dummy element's innerHTML called "doo" (which is not available in your code snippet above, causing that you see no output when you run the snippet)
now, you want to open this link? or iframe it? easy..
var myLink = 'http://anylink.com/' + randString(4);
window.open(myLink); // this will open the link in a new window/tab
or an iframe would be like this
var myLink = 'http://anylink.com/' + randString(4);
var myIframe = document.createElement('iframe');
myIframe.src = myLink;
document.body.appendChild(myIframe);
é voilà :)
oh and if you want to "rotate" your iframe - this would be a CSS task - a CSS definition for the iframe like this for example:
iframe {
transform: rotateZ(45deg);
}

Add certain end to all the internal links on the page

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.

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);
}

How to stop Javascript from showing default image and only text for link?

The Javascript below has a default image, but I would like display text "only text url" for this link instead of this button at this link http://developer.mixi.co.jp/wp-content/uploads/2010/09/bt_check_1.gif that this script defaults to. Is this possible?
<div>
only text url
<script type="text/javascript" src="http://static.mixi.jp/js/share.js"></script>
</div>
Assuming this is legal (it may not be legal to embed this script in your site if you make modifications to it), we can decompress the script using an online JavaScript beautifier. The result is this:
http://www.jsfiddle.net/T4Rrh/
The bit we're interested in is the last for loop there, where each button is processed. We can safely remove a most of the image generation and protocol sniffing (an unnecessary practice, by the way) to reduce the weight of the code:
var type = (button["button"] || "button-1.png").split("-");
var prefix = ("https:" == document.location.protocol) ? "https://mixi.jp/" : "http://static.mixi.jp/";
if (!type || type.length < 2) type = ["button", "1.png"];
if (type[1].indexOf(".") == -1) type[1] += ".png";
var src = (type[0] == "button") ? [prefix, "img/basic/mixicheck_entry/bt_check_", type[1]] : (type[0] == "icon") ? [prefix, "img/basic/mixicheck_entry/icon_mixi_", type[1]] : [prefix, "img/basic/mixicheck_entry/bt_check_1.png"];
src = src.join("");
and
var img = document.createElement("img");
img.setAttribute("src", src);
img.style.border = "0";
var element = button.element;
for (var j = element.childNodes.length - 1; j >= 0; j--) {
element.removeChild(element.childNodes[j]);
}
element.appendChild(img);
should be both removed. You can then minify and save the code, then serve it yourself in your page. Here's what the cleaned up code looks like: http://www.jsfiddle.net/XrYLX/
Second Method:
Using CSS, we first remove the part of the JavaScript which removes all child nodes of the button element, so the text inside the button is not removed:
for (var j = element.childNodes.length - 1; j >= 0; j--) {
element.removeChild(element.childNodes[j]);
}
We then apply some CSS to hide the image:
.mixi-check-button img {
display: none;
}
See: http://www.jsfiddle.net/T4Rrh/1/.
Copy that script to your site and remove element.appendChild(img); at the beginning of the last line.

Categories

Resources