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/
Related
I am using a javascript on my site, which always inherits the UTM parameters to the links on the site.
However, this is not working, when the links are anchor links to a section of the site and the link the visitor used to visit the page contains the "gclid" parameter from google.
For example:
A visitor uses this link to visit a site:
domain.com?utm_source=test&utm_medium=test&utm_campaign=test&gclid=12345
The button link on the site with the anchor link will look like the following:
domain.com&gclid=12345?utm_source=test&utm_medium=test&utm_campaign=test#anchor
For some reason the "&gclid" part changes its position.
I've tested it with a link without an anchor and in this case the "gclid" parameter doesn't get inherited and the link works.
Of course, the second domain isn't working anymore and leads to a 404 error.
Does someone have an idea what could be the cause for this?
This is the javascript I am using to inherit the UTMs:
(function() {
var utmInheritingDomain = "grundl-institut.de"
utmRegExp = /(\&|\?)utm_[A-Za-z]+=[A-Za-z0-9]+/gi,
links = document.getElementsByTagName("a"),
utms = [
"utm_medium={{URL - utm_medium}}",
"utm_source={{URL - utm_source}}",
"utm_campaign={{URL - utm_campaign}}"
];
for (var index = 0; index < links.length; index += 1) {
var tempLink = links[index].href,
tempParts;
if (tempLink.indexOf(utmInheritingDomain) > 0) {
tempLink = tempLink.replace(utmRegExp, "");
tempParts = tempLink.split("#");
if (tempParts[0].indexOf("?") < 0) {
tempParts[0] += "?" + utms.join("&");
} else {
tempParts[0] += "&" + utms.join("&");
}
tempLink = tempParts.join("#");
}
links[index].href = tempLink;
}
}());
EDIT: It seems like the following script don`t causes this problem:
<script>
(function() {
var domainsToDecorate = [
'domain.com',
],
queryParams = [
'utm_medium',
'utm_source',
'utm_campaign',
]
var links = document.querySelectorAll('a');
for (var linkIndex = 0; linkIndex < links.length; linkIndex++) {
for (var domainIndex = 0; domainIndex < domainsToDecorate.length; domainIndex++) {
if (links[linkIndex].href.indexOf(domainsToDecorate[domainIndex]) > -1 && links[linkIndex].href.indexOf("#") === -1) {
links[linkIndex].href = decorateUrl(links[linkIndex].href);
}
}
}
function decorateUrl(urlToDecorate) {
urlToDecorate = (urlToDecorate.indexOf('?') === -1) ? urlToDecorate + '?' : urlToDecorate + '&';
var collectedQueryParams = [];
for (var queryIndex = 0; queryIndex < queryParams.length; queryIndex++) {
if (getQueryParam(queryParams[queryIndex])) {
collectedQueryParams.push(queryParams[queryIndex] + '=' + getQueryParam(queryParams[queryIndex]))
}
}
return urlToDecorate + collectedQueryParams.join('&');
}
// borrowed from https://stackoverflow.com/questions/831030/
// a function that retrieves the value of a query parameter
function getQueryParam(name) {
if (name = (new RegExp('[?&]' + encodeURIComponent(name) + '=([^&]*)')).exec(window.location.search))
return decodeURIComponent(name[1]);
}
})();
</script>
You really should not change URLs with regexp and string manipulation.
Here is the recommended way
const url = new URL(location.href); // change to tempLink
utms = [
"utm_medium=med",
"utm_source=src",
"utm_campaign=camp"
];
utms.forEach(utm => url.searchParams.set(...utm.split("=")))
console.log(url.toString())
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
});
I am using JSON to display info from a site. The book example works which gave me a custom website to get information from worked, but when I replaced the url with Spider man's facebook page, it seems as if the data is processing, but the information does not display. Is there some crucial step that I am missing.
var lastReporttime = 0;
window.onload= function(){
setInterval(handleRefresh,3000);
}
function updateSales(sales) {
var salesDiv= document.getElementById("sales");
for (var i = 0; i < sales.length; i++) {
var sale = sales[i];
var div = document.createElement("div");
div.innerHTML = sale.category + sale.about + "spiderman";
salesDiv.appendChild(div);
}
if (sales.length > 0) { lastReporttime = sales[sales.length-1].time; }
}
function handleRefresh() {
var url = "http://graph.facebook.com/SpiderManDVD"
+ "callback=updateSales"
+ "&lastreporttime=" + lastReporttime
+ "&random="+ (new Date()). getTime();
var newScriptElement= document.createElement("script");
newScriptElement.setAttribute("src", url);
newScriptElement.setAttribute("id", "jsonp");
var oldScriptElement= document.getElementById("jsonp");
var head= document.getElementsByTagName("head")[0];
if (oldScriptElement == null) {
head.appendChild(newScriptElement);
} else {
head.replaceChild(newScriptElement, oldScriptElement);
}
}
Response you received from your book example returns a JSON Array which is perfectly handled in your code.
But response from facebook api returns a JSON object which is breaking your code.
Check both the urls and update the logic inside updateSales to handle both JSON Array as well as JSONObject as per your use case.
Something like this
function updateSales(sales) {
var salesDiv= document.getElementById('sales');
// Check if sales is array or not (One of the crude ways, ofcourse not best but may work for you)
if (typeof sales.length == 'undefined') {
sales = [sales];
}
for (var i = 0; i < sales.length; i++) {
var sale = sales[i];
var div = document.createElement("div");
div.innerHTML = sale.category + sale.about + "spiderman";
salesDiv.appendChild(div);
}
if (sales.length > 0) {
lastReporttime = sales[sales.length-1].time;
}
}
I am more familiar with CSS coding than with Javascript, so when I was tasked to find a way to display Link URLS during print but not on-screen, I ran into a bit of trouble. Using CSS, I can manage what I want just fine, but thanks to Internet Explorer's quirkiness, I've had to find a javascript solution to my problem.
I was able to solve my dilemma with this code to make the link URLs display on print, and then disappear off the page when print preview was closed.
window.onbeforeprint = function(){
var links = document.getElementsByTagName("a");
for (var i=0; i< links.length; i++){
var theContent = links[i].getAttribute("href");
if (!theContent == ""){
links[i].newContent = " [" + theContent + "] ";
links[i].innerHTML = links[i].innerHTML + links[i].newContent;
}
}
}
window.onafterprint = function(){
var links = document.getElementsByTagName("a");
for (var i=0; i< links.length; i++){
var theContent = links[i].innerHTML;
if (!theContent == ""){
var theBracket = theContent.indexOf(links[i].newContent);
var newContent = theContent.substring(0, theBracket);
links[i].innerHTML = newContent;
}
}
}
However, now my problem becomes that ALL the page link URLs are printed. But, obviously, I don't need to print things like the internal navigation URLs; that just makes the finished product look messy. Is there a way to exclude certain sections of the page, like a UL-list with the ID of Navigation, from the onbeforeprint/onafterprint functions in javascript?
getElementsByTagName can be used as a method of any DOM node.
Thus:
var links = document.getElementById('showURLs').getElementsByTagName('a');
Using an ID on the parent
Simply replace the variable definition for links in your code with the above. Like so:
window.onbeforeprint = function(){
var links = document.getElementById('showURLs').getElementsByTagName('a');
for (var i=0; i< links.length; i++){
var theContent = links[i].getAttribute("href");
if (!theContent == ""){
links[i].newContent = " [" + theContent + "] ";
links[i].innerHTML = links[i].innerHTML + links[i].newContent;
}
}
}
window.onafterprint = function(){
var links = document.getElementById('showURLs').getElementsByTagName('a');
for (var i=0; i< links.length; i++){
var theContent = links[i].innerHTML;
if (!theContent == ""){
var theBracket = theContent.indexOf(links[i].newContent);
var newContent = theContent.substring(0, theBracket);
links[i].innerHTML = newContent;
}
}
}
Excluding children of a specific element
window.onbeforeprint = function(){
var links = document.getElementsByTagName("a");
var exclude = document.getElementById("navBar").getElementsByTagName("a");
for (var i=0; i< links.length; i++) {
if (!in_array(links[i], exclude)) {
var theContent = links[i].getAttribute("href");
if (!theContent == "") {
links[i].newContent = " [" + theContent + "] ";
links[i].innerHTML = links[i].innerHTML + links[i].newContent;
}
}
}
}
We get an array of all links on the page and one of links in the exclusion element (here with an ID of "navBar"). Then, when we are looping through the links on the page, we first check if they're in the exclusion array, and only if they're not we act!
For that conditional we use the bool in_array(needle, haystack) function, which returns true if the needle is found in the haystack (an array), false otherwise. This function is actually an adaptation of PHP's native function - see PHP manual.
function in_array(needle, haystack) {
for (i=0;i<haystack.length;i++) {
if (haystack[i] == needle) {
return true;
}
}
return false;
}
See this JSfiddle I created to test it. If you run print preview in your browser, you'll be able to see the links on the right!
Hope this helps :)
So guys, I try to make this work. When I click on a button on a page, it has to transfer the array to another page to show it. My functions addProduct, showProduct, addItem and button work. But My data from the array does not get passed to the other page. So when I click on a button in page A, a value is added to this array. But on page B it shows that the array is empty
var products = new Array();
window.addEventListener("load", loadPage, false);
window.addEventListener("load", addButton, false);
window.addEventListener("load", showProducts, false);
function addButton() {
var button = document.getElementById("sell");
button.addEventListener("click", addItem, false);
}
function loadPage(){
getCookie();
}
function getCookie(){
var elements = document.cookie.split('=');
var products_cookie = elements[1].split('%');
for(var i=0;i < products_cookie.length-1;i++) {
var tmp = products_cookie[i].split('$');
addProduct(tmp[0], tmp[1], tmp[2]);
}
}
function setCookie(){
var date = new Date();
date.setTime(date.getTime()+(2592000)); //expire time = 30 dagen nadat cookie aangemaakt is
var expires = "; expires="+date.toGMTString()
var text = "";
for (var i = 0; i < products.length; i++){
text+= products[i][0] + "$" + products[i][1] + "$" + products[i][2] +"%"; // slaat naam $ aantal $ prijs op
}
document.cookie = "tradepoint"+text+expires;
}
function addProduct(pName, pAmount, pPrice){
var product = new Array(pName, parseInt(pAmount), pPrice);
products[products.length] = product;
setCookie();
}
function addItem(){
addProduct("andrej", 2, 1);
alert(products + " " + products.length);
}
function showProducts(){
if (products.length != 0){
document.getElementById("shopList").innerHTML = "<ul><li>Full</li></ul>";
}
else{
document.getElementById("shopList").innerHTML = "<ul><li>Empty</li></ul>";
}
}
Cookies are represented as name=value pairs, your setCookie function doesn't do that you should have document.cookie = "tradepoint="+text+expires; notice the = sign.
Also your getCookie function may not work if there are other cookies being set.
Are you testing this against localhost? Cookies will not "stick" to TLDs. You need at least x.y.z - use an alias to 127.0.0.1 in your hosts file to test cookie related code.
(stackoverflow won't let me post an url to localhost - anti-trolling technology I presume!)