Searching an external URL for files with javascript - javascript

I am building a page that needs to be able to get a all the file links on a webpage and add them to a dropdown list. Original it was the script was supposed to be on the same page as the files but now it needs to search an external. This is what I used before the change
<script>
$(document).ready(function() {
var arr = [];
var filenames = [];
var alt_var;
var baseURL = "www.fakeurl.com"
$('.ms-vb-icon').find('a').each(function(){
var temp = $(this).attr('href')
$(this).find('img').each(function(){
alt_var = $(this).attr('alt');
});
if(temp.indexOf('.csv') != -1){arr.push(temp); filenames.push(alt_var);}
});
for(i = 0; i < arr.length; ++i)
{
var x = document.createElement('li');
var a = document.createElement('a');
var t = document.createTextNode(" " + filenames[i]);
var fullURL = baseURL + arr[i];
a.setAttribute('href',"#");
a.setAttribute('class', "glyphicon glyphicon-file");
a.setAttribute('id', baseURL + arr[i]);
a.setAttribute('onclick', "drawChart(this.id)");
a.appendChild(t);
x.appendChild(a);
document.getElementById("dropdownfiles").appendChild(x);
}
});
</script>
How can I change this to search an external url. (PS new to Javascript)

Not sure if this is the cleanest way but you could add a hidden iframe on the page and then search in there.
css:
.externalSearcher iframe {
display: none;
}
html:
<div class="externalSearcher"></div>
js:
$('.externalSearcher').append('<iframe src="' + externalLink + '"></iframe>');
$('.externalSearcher').find('a').each(function () {
//do what you want with the link
});

Related

Overwrite UTM Parameter

We do have some Campaigns (Google, facebook,...) When the user arrives the landingpage (abo.mysite.com) he does have the utm parameter utm_source=theCampaignSource. When the user clicks an CTA the CTA gives an new UTM utm_source=abo and he goes to shop.mysite.com.
We are not able to remove the UTM from abo.mysite.com.
Is there a way to check if a user have already an UTM, and when he does have one to kepp them until shop.mysite.com? So we know that the user is comming from Google (...)?
We know that how this Thing is set up is a very bad practice, and we are working on it.
Ive found a code snippet which is manipulating the links on a site:
links.forEach(function(link){
link.setAttribute("href","abo.mysite.com")
})
but i couldn get it work - cause i do have a lack of experience.
Update
To my specific needs a made it that way:
1) Remove existing UTM from Links on the Site
<script>
var link = document.getElementsByTagName("a");
for (var i = 0; i < link.length; i++) {
link[i].href = link[i].href.replace(/(\?)utm[^&]*(?:&utm[^&]*)*&(?=(?!utm[^\s&=]*=)[^\s&=]+=)|\?utm[^&]*(?:&utm[^&]*)*$|&utm[^&]*/gi, '$1');
}
</script>
2) Hash the UTM in the URL
<script>
if(!window.jQuery) {
document.write('<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js">\x3C/script>');
}
</script>
<script type="text/javascript">
$(document).ready(function() {
function getUrlVars() {
var vars = [],
hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for (var i = 0; i < hashes.length; i++) {
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
var parameters = getUrlVars();
var utm_source = decodeURIComponent(parameters['utm_source']);
var utm_campaign = decodeURIComponent(parameters['utm_campaign']);
var utm_medium = decodeURIComponent(parameters['utm_medium']);
</script>
3)rewrite every URL on the Site with the hashed UTMs
<script>
$('a').each(function(){
$(this).attr('href', $(this).attr('href') + '?utm_source=' + utm_source + '&utm_campaign' + utm_campaign + '&utm_medium' + utm_medium);
});
});
Edit
Thanks to Michele Pisani
this works well - BUT, if a user does not have an UTM, and he clicks the button, the UTM will be set to undefined
Is there a way to set the UTM Parameter from the URL when the User already has one, or to use the existing UTM (which are hardcoded in the button) when he does not have an UTM in the URL.
Edit 2 & update
Finally - with the help of you guys - i found a solution:
<script>
var link = document.querySelectorAll('a:not([href*="#"])');
for (var i = 0; i < link.length; i++) {
//link[i].href = link[i].href.replace(/(\?)utm[^&]*(?:&utm[^&]*)*&(?=(?!utm[^\s&=]*=)[^\s&=]+=)|\?utm[^&]*(?:&utm[^&]*)*$|&utm[^&]*/gi, '$1');
}
</script>
<script type="text/javascript">
$(document).ready(function() {
function getUrlVars() {
var vars = [],
hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for (var i = 0; i < hashes.length; i++) {
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
//var parameters = getUrlVars();
//var utm_source = decodeURIComponent(parameters['utm_source']);
//var utm_campaign = decodeURIComponent(parameters['utm_campaign']);
//var utm_medium = decodeURIComponent(parameters['utm_medium']);
var url_string = window.location.href; //window.location.href
var url = new URL(url_string);
//var c = url.searchParams.get("c");
var utm_source = url.searchParams.get("utm_source");
var utm_campaign = url.searchParams.get("utm_campaign");
var utm_medium = url.searchParams.get("utm_medium");
$('a:not([href^="#"])').each(function() {
if(utm_source != "" && utm_source != null){
var href = $(this).attr("href");
href = href.replace(/(\?)utm[^&]*(?:&utm[^&]*)*&(?=(?!utm[^\s&=]*=)[^\s&=]+=)|\?utm[^&]*(?:&utm[^&]*)*$|&utm[^&]*/gi, '$1');
$(this).attr("href",href);
$(this).attr('href', $(this).attr('href') + '?utm_source=' + utm_source + '&utm_campaign=' + utm_campaign + '&utm_medium=' + utm_medium);
}
});
});
</script>
With JavaScript, to remove UTM parameters from links in page you can try this function with regex:
var link = document.getElementsByTagName("a");
for (var i = 0; i < link.length; i++) {
link[i].href = link[i].href.replace(/(\?)utm[^&]*(?:&utm[^&]*)*&(?=(?!utm[^\s&=]*=)[^\s&=]+=)|\?utm[^&]*(?:&utm[^&]*)*$|&utm[^&]*/gi, '$1');
}
If you are using Google Tag Manager you can add it in a custom HTML tag and fires it on DOM Ready.
If you want to keep the fragment in the URL you can modify the function in this way:
var link = document.getElementsByTagName("a");
for (var i = 0; i < link.length; i++) {
arr_link = (link[i].href).split("#");
var fragment = "";
if (arr_link[1]) { fragment = "#" + arr_link[1]; }
var my_new_url = arr_link[0].replace(/(\?)utm[^&]*(?:&utm[^&]*)*&(?=(?!utm[^\s&=]*=)[^\s&=]+=)|\?utm[^&]*(?:&utm[^&]*)*$|&utm[^&]*/gi, '$1');
link[i].href = my_new_url + fragment;
}
const ourUTMs = new URL(location.href).searchParams;
document.body.onclick = (e) => {
if (!isParamsContainsUTM(ourUTMs) || e.target.tagName !== "A") {
return;
}
try {
// Is valid url?, else we go to catch =)
const url = new URL(e.target.href);
e.preventDefault();
// Remove all utm params from link;
Array.from(url.searchParams).forEach(([k]) => {
if (k.startsWith("utm_")) {
url.searchParams.delete(k);
}
});
// Add our utm_ params to link
Array.from(ourUTMs).forEach(([k, v]) => {
url.searchParams.append(k, v);
});
// Open URL
window.open(url.toString());
} catch (e) {}
};
const isParamsContainsUTM = (arr = new URLSearchParams()) =>
Array.from(arr).some(([key]) => key.startsWith("utm_"));

Simple breadcrumb

I have this code of a breadcrumb that I found, but it shows the whole link. How can I make a similar simple breadcrumb that shows only the name of the page based on the path? (only in JavaScript)
(it would be good to change the background color too)
<SCRIPT LANGUAGE="JavaScript">
var path = "";
var href = document.location.href;
var s = href.split("/");
for (var i=2;i<(s.length-1);i++) {
path+=""+s[i]+" / ";
}
i=s.length-1;
path+=""+s[i]+"";
var url = window.location.protocol + "//" + path;
document.writeln(url);
</script>
do you mean that it will not include the site in the breadcrumbs??
<script language="Text/JavaScript">
var path = "";
var href = document.location.href;
var s = href.split("/");
for (var i=2;i<(s.length-1);i++) {
path+=""+(i == 2 ? "home" : s[i])+" / ";
}
i = s.length-1;
path += ""+s[i]+"";
var url = path;
document.writeln(url);
</script>

How to get a list of downloads using the Chrome.downloads api?

I've created an extension and I want it to list all of the downloads in the user's downloads folder on a page rather than just opening the download folder.
This is my code:
window.onload = function(){
var maxNumOfEntries = 100;
for(i = 0; i < maxNumOfEntries; i++){
para = document.createElement('p');
para.setAttribute("id", ("download" + i));
var node = document.createTextNode("");
para.appendChild(node);
var element = document.getElementById("content");
var child = document.getElementById("stuff");
element.insertBefore(para,child);
}
var num = 0;
var currentTime = new Date().getTime();
chrome.downloads.search({text: '', limit: 100}, function(data) {
data.forEach(function(DownloadItem) {
document.getElementById('download' + num).innerHTML = DownloadItem.filename;
num++;
});
});
}
I've tried various other methods but I just can't seem to get the downloads to appear, any advice?
The text property should not be there, which is causing the problem.
chrome.downloads.search({limit: 100}, function(data) {
data.forEach(function(item, i) {
document.getElementById('download' + i).innerHTML = item.filename;
});
});

I have a slideshow working to change the images, however how do i add a seperate html page link to each image

var index=0;
var titles=[1,2,3,4];
function moveToNextSlide()
{
if (index >= 4){index=0}
var img = document.getElementById("img1");
var slideName="images/img" + titles[++index] + ".jpg";
img.src=slideName;
}
function moveToPreviousSlide()
{
if (index <= 0){index=4}
{
var img = document.getElementById("img1");
var slideName="images/img" + titles[--index] + ".jpg";
img.src=slideName;
}
}
That is the javascript code for my slideshow and in my html I have used input buttons next and back to call the image change.
How do I add a random html link so when I click on a image it goes to a different html page?
Surround your <img> tag inside an <a> like this:
<img id="img1" src="images/img1.jpg">
Now in both the methods add code to update the href of the tag accordingly.
var urls=["http://www.example.com","http://www.example2.com","http://www.example3.com","http://www.example4.com"];
function moveToNextSlide()
{
if (index >= 4){index=0}
var img = document.getElementById("img1");
var slideName="images/img" + titles[++index] + ".jpg";
img.src=slideName;
var link= document.getElementById("link1");
var url=urls[++index];
link.href=url;
}
function moveToPreviousSlide()
{
if (index <= 0){index=4}
{
var img = document.getElementById("img1");
var slideName="images/img" + titles[--index] + ".jpg";
img.src=slideName;
var link= document.getElementById("link1");
var url=urls[++index];
link.href=url;
}
}
Try and tell.

How do I get this code to work on google sites?

I have this code:
var links = [cant put links in yet] var visited = [];
var button = document.getElementById('btn');
button.addEventListener('click', function() {
if (visited.length == links.length) {
alert('You visited all the links');
return;
}
var random, url;
do {
random = Math.floor(Math.random() * 4);
url = links[random];
} while (contains(visited, url));
alert('Opening: ' + url + ' with #' + random);
visited.push(url);
var win = window.open(url, '_blank');
win.focus(); });
function contains(array, value) {
for (var i = 0; i < array.length; i++) {
if (array[i] == value) return true;
}
return false;
}
and I need to combine it together and put it on to a google site. I tried combing it all with tags in an html box, but all that does is create my button. It doesn't run the script and open the links... Will this code not work on google sites or am I doing it wrong?
FULL CODE w/html and css
On the Html Box , you can't.
You can use this code with App Engine or use Google App SCript.
you can see an example here : http://tutorialzine.com/2011/01/google-appengine-series/

Categories

Resources