Being a Javascript novice I am having some trouble implementing Google's Adwords GCLID tracking on our site. I am following their code examples show here https://support.google.com/adwords/answer/2998031.
You can see the cookie being stored but when trying to retrieve it and populate a hidden form field the result is just blank. I have used other variations but that simply results in "Undefined" as the field value.
Here is the code I'm using
Simplified HTML Form
<form class="signup-form" name="signupform" method="post" action="step2.php">
<input type="hidden" name="gclid" id="gclid" value="" />
</form>
Cookie Write Script
<script type="text/javascript">
function setCookie(a,d,b){var c=new Date;c.setTime(c.getTime()+864E5*b);b=";
expires="+c.toGMTString();document.cookie=a+"="+d+b}function getParam(a) {return(a=RegExp("[?&]"+a+"=([^&]*)").exec(window.location.search))&&decodeURIComponent(a[1].replace(/\+/g," "))}var gclid=getParam("gclid");if(gclid){var gclsrc=getParam("gclsrc");(!gclsrc||-1!==gclsrc.indexOf("aw"))&&setCookie("gclid",gclid,90)};
</script>
Cookie Read Script
<script>
function readCookie(name) {
var n = name + "=";
var cookie = document.cookie.split(';');
for(var i=0;i < cookie.length;i++) {
var c = cookie[i];
while (c.charAt(0)==' ') {
c = c.substring(1,c.length);
}
if (c.indexOf(n) == 0){
return c.substring(n.length,c.length);
}
}
return null;
}
function() {
document.getElementById('gclid').value = readCookie('gclid');
}
</script>
function() {
document.getElementById('gclid').value = readCookie('gclid');
}
this is a function without a name that's never called. try replacing it with only
document.getElementById('gclid').value = readCookie('gclid');
I rewrote your write script, I think your cookie is never set.
function setCookie(a,d,b) {
var c = new Date;
c.setTime(c.getTime()+864E5*b);
b="; expires=" + c.toGMTString();
document.cookie = a + "=" + d + b
}
function getParam(a) {
return(a=RegExp("[?&]"+a+"=([^&]*)").exec(window.location.search))&&decodeURIComponent(a[1].replace(/\+/g," "))
}
var gclid=getParam("gclid");
if(gclid) {
var gclsrc = getParam("gclsrc");
if(!gclsrc||-1 !== gclsrc.indexOf("aw")) {
setCookie("gclid", gclid, 90);
alert("Cookie Set!");
}
}
Working script modified from https://support.google.com/adwords/answer/3285060. I just changed the document.onload to window.onload It seems there was too much going on off screen in the DOM.
<script>
window.onload = function getGclid() {
document.getElementById("gclid").value = (name = new
RegExp('(?:^|;\\s*)gclid=([^;]*)').exec(document.cookie)) ?
name.split(",")[1] : ""; }
</script>
Related
I recently was given a solution to checking if a pop up has been shown and then only showing it once using cookies. But after implementing cookies the pop up no longer shows. I have googled the issue, and tried to find a solution but my lack of knowledge on the subject has made it difficult for me to understand the issue and fix it.
This is the code i am using, i have implemented the use of cookies and i believe that they should work but the pop up however is not working
function setCookie(cname,cvalue) {
document.cookie = cname + "=" + cvalue;
}
function getCookie(cname) {
var name = cname + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.split(';');
for(var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
function checkCookie() {
var user=getCookie("ageverification");
if (user != "") {
return null;
} else {
var overlay = $('<div id="overlay"></div>');
overlay.show();
overlay.appendTo(document.body);
$('.popup').show();
$('.close').click(function() {
$('.popup').hide();
overlay.appendTo(document.body).remove();
return false;
user = true;
setCookie("ageverification", user);
});
}
}
function goBack() {
window.history.go(-2);
}
<div class='popup'>
<div class='cnt223'>
<h1>Important Notice</h1>
<p>
You must be over 18 to Purchase products on this website!
<br/>
<br/>
I Am Over 18
I Am Not
</p>
</div>
</div>
I applied some changes to your code and now it should work.
As a summary, I applied these changes:
removed dead code from checkCookie;
simplified the code for getCookie;
eliminated the overlay div (which did nothing: it was just created empty, attached to the DOM and then removed from it);
changed "popup" from a class to an id;
made the selector strings more specific.
To improve the getCookie function, I eliminated an unnecessary loop and a few substrings. You can get to the same result more cleanly using the trim method (which eliminates preceding and trailing whitespace from a string) and splitting the cookie by "=".
To improve checkCookie, I eliminated some dead code (which couldn't run because it was after a return statement), some redundant one (which declared variables for values needed only once) and the apparently useless div tag. Also, I changed the selector strings to explicitly reference the "a" node inside the popup and I added a call to preventDefault(). This last part (changing the selector strings and calling preventDefault) was the one solving the issue.
function setCookie(cname,cvalue) {
document.cookie = cname + "=" + cvalue;
}
function getCookie(cname) {
var ca = decodeURIComponent(document.cookie).split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i].trim().split('=');
if (cname == c[0] && c.length > 1) {
return c[1];
}
}
return "";
}
function checkCookie() {
if (getCookie("ageverification") == ""){
$('#popup').show();
$('#popup a.close').click(function (event) {
event.preventDefault();
$('#popup').hide();
setCookie("ageverification", 'true');
});
$('#popup a.goBack').click(function ( event ) {
event.preventDefault();
goBack();
});
} else {
return null;
}
}
function goBack() {
window.history.go(-2);
}
<div id='popup'>
<div class='cnt223'>
<h1>Important Notice</h1>
<p>
You must be over 18 to Purchase products on this website!
<br/>
<br/>
I Am Over 18
I Am Not
</p>
</div>
</div>
After click on button in first.html, i have been called a function and updated labels in second.html, but i able to see a second.html not able to see the updated value in labels in second.html.Please help me how to achieve.
function updateLabels(){
$('#entryNumber').text("123");
$('#responsedate').text("23-9-2015");
window.location = 'second.html';
}
ex:second.html
<body>
<label>Entry Number:</label>
<label id="entryNumber" for="entryNumber"></label><br><br>
<label>Respond Date:</label>
<label id="responsedate" for="responsedate"></label><br><br>
<label>Response Text:</label>
</body>
You can achieve your goal in client side via.. 3 options
1. By Local Storage
On first page set your second page label value in local storage.
// In 1st page
function updateLabels(){
localStorage.setItem('Second_Page_LabelVal', "apple");
window.location = 'second.html';
}
On second Page get this value from local storage and set it to your labels value
// In 2ndPage
$( document ).ready(function() {
// Retrieve the object from storage
var retrievedVal = localStorage.getItem('Second_Page_LabelVal');
$("2ndpagelabelId").text(retrievedVal);
});
2. By cookie
On first page set your second page label value in COOKIES.
function createCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
// In 1st page
function updateLabels(){
createCookie(('Second_Page_LabelVal', "apple",1);
window.location = 'second.html';
}
On second Page get this value FROM COOKIE and set it to your labels value
// In 2ndPage
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return
c.substring(nameEQ.length,c.length);
}
return null;
}
$( document ).ready(function() {
// Retrieve the object from cookie
var retrievedVal = readCookie('Second_Page_LabelVal');
$("2ndpagelabelId").text(retrievedVal);
});
3. By querystring Url
Redirect page with second page value in query string
// In 1st page
function updateLabels(){
window.location = 'second.html?SecondpageValue=value1';
}
Get the value from url and set it to label.
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results === null ? "" :
decodeURIComponent(results[1].replace(/\+/g, " "));
}
$( document ).ready(function() {
// Retrieve the object from url
var retrievedVal = getParameterByName('SecondpageValue');
$("2ndpagelabelId").text(retrievedVal);
});
Html page DOES NOT save your status, and we needs a server-side program to handle usually.
In your case, maybe a modal dialog is useful.
Try using $.get() , substitute .replaceWith() for window.location at same document
function updateLabels(html){
$(html).find("#entryNumber").text("123");
$(html).find("#responsedate").text("23-9-2015");
$("body").replaceWith(html);
}
$.get("second.html", updateLabels);
I'm working on a page that refreshes itself every 5 minutes
<meta http-equiv="refresh" content="1200;url=?meta_refresh=true" />
On the page is a JS script that should run the first two times the page reloads. When the page reload's for the third time, the script should not execute.
So far, I've created a cookie and given it an initial value of 0, for every refresh I increment it's value (rewrite the cookie) and if the value is smaller than 3 i execute the part of a script. The things is that if I close the tab and reopen the page in another tab, the cookie has the incremented value, and I want it to always start from 0.
Here's what i've done so far:
var value = 0;
$(document).ready(function() {
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1);
if (c.indexOf(name) == 0) return c.substring(name.length,c.length);
}
return "";
}
function checkCookie() {
var cookieValue = getCookie('siteRefreshCookie');
if (cookieValue !== '') {
var newValue = parseInt(getCookie('siteRefreshCookie')) + 1;
if (newValue < 3) {
//script to be executed
document.cookie = "siteRefreshCookie="+ newValue +";";
}
} else {
document.cookie = "siteRefreshCookie="+ value +";";
}
}
checkCookie();
})
Could I suggest using a query string instead?
<meta http-equiv="refresh" content="1200;url=?meta_refresh=true&count=1" />
Then as an ASP programmer myself I would do something like:
<meta http-equiv="refresh" content="1200;url=?meta_refresh=true&count=<%=CInt(0 & Request.Querystring("count")) + 1%>" />
But you can probably achieve this using PHP, or even JS I imagine if you have no back-end language suitable.
The problem with using cookies is that they are tied to that website, rather than that window. Even if you reset the cookie with an unload function like Pete suggested, you'll then run into problems like if for example you have two tabs open with the same page.
For example:
<script>
$(document).ready( function() {
alert( $(this).getBelowElementToThisScript('form').id );
});
</script>
<form id="IamTheNext"></form>
<form id="Iamnot"></form>
This code should show this message: IamTheNext
In addition, the solution needs to work with this example too:
<script src="getbelowelement.js"></script>
<form id="IamTheNext"></form>
<form id="Iamnot"></form>
Thanks
Try this:
var form = $('script[src="getbelowelement.js"]').next();
But I would suggest using the forms id:
var form = $('#IamTheNext');
You could also try giving the script tag an id.
This kind of approach is dangerous; script should never depend that much on where it is in the page.
That said, the following works in Firefox and Chrome and should work in the major browsers (use at your own risk).
See it in action at jsBin. Both <script> ... and <script src="..."> approaches are shown in the same page.
$(document).ready( function () {
invocationsOfThis = (typeof invocationsOfThis == 'number') ? invocationsOfThis + 1 : 1;
var scriptTags = document.getElementsByTagName ('script');
var thisScriptTag = null;
//--- Search scripts for scripts of this type.
for (var foundCnt = 0, J = 0, L = scriptTags.length; J < L; ++J)
{
/*--- Since the script can be either inline or included, search
both the script text and the script src link for our unique
identifier.
*/
var thisTag = scriptTags[J];
var scriptCode = thisTag.innerText || thisTag.textContent;
var scriptSrc = thisTag.src;
//--- IMPORTANT, change pastebin.com to the filename that you use.
if (/invocationsOfThis/i.test (scriptCode) || /pastebin.com/i.test (scriptSrc))
{
//--- Found a copy of this script; is it the right one, based on invocation cnt?
foundCnt++;
if (foundCnt == invocationsOfThis) {
thisScriptTag = thisTag;
break;
}
}
}
if (thisScriptTag) {
//--- Get the target node.
var nextForm = $(thisScriptTag).next ('form');
var nextFormId = nextForm.attr ('id');
//--- Act on the target node. Here we notify the user
nextForm.text ('This is form: "' + nextFormId + '".');
}
} );
I wrote simplest extension as an exercise in JS coding. This extension checks if some user (of certain social network) is online, and then outputs his/her small image, name and online status in notification alert. It checks profile page every 2 minutes via (setTimeout), but when user becomes "online", i set setTimeout to 45 minutes.(to avoid online alerts every 2 minutes).
It works, but not exactly as i expected. I have 2 issues:
1)When certain user is online and i change user id (via options page) to check another one, it doesnt happen because it waits 45 or less minutes. i tried the following code (in options.html), but it doesnt help.
2)When i change users, image output doesnt work correctly!! It outputs image of previous user!!
How do i fix these problems??
Thanks!
options.html
<script>
onload = function() {
if (localStorage.id){
document.getElementById("identifier").value = localStorage.id;
}
else {
var el = document.createElement("div");
el.innerHTML = "Enter ID!!";
document.getElementsByTagName("body")[0].appendChild(el);
}
};
function onch(){
localStorage.id = document.getElementById("identifier").value;
var bg = chrome.extension.getBackgroundPage();
if(bg.id1){
clearTimeout(bg.id1);
bg.getdata();
}
}
</script>
<body>
<h1>
</h1>
<form id="options">
<h2>Settings</h2>
<label><input type='text' id ='identifier' value='' onchange="onch()"> Enter ID </label>
</form>
</body>
</html>
backg.html
<script type="text/javascript">
var domurl = "http://www.xxxxxxxxxxxxxx.xxx/id";
var txt;
var id1;
var id2;
var imgarres = [];
var imgarr = [];
var imgels = [];
function getdata() {
if (id1){clearTimeout(id1);}
if (id2){clearTimeout(id2);}
var url = getUrl();
var xhr = new XMLHttpRequest();
xhr.open('GET',url, true);
xhr.setRequestHeader('Cache-Control', 'no-cache');
xhr.setRequestHeader('Pragma', 'no-cache');
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
txt = xhr.responseText;
var r = txt.indexOf('<b class="fl_r">Online</b>');
var el = document.createElement("div");
el.innerHTML = txt;
var n = imgprocess(el,url);
var nam = el.getElementsByTagName("title")[0].innerHTML;
if (r != -1) {
var notification = webkitNotifications.createNotification(n, nam, 'online!!' );
notification.show();
var id1 = setTimeout(getdata, 60000*45);
}
else {
var id2 = setTimeout(getdata, 60000*2);
}
}}
xhr.send();
}
function imgprocess(text,url){
imgels = text.getElementsByTagName("IMG");
for (var i=0;i< imgels.length;i++){
if (imgels[i].src.indexOf(parse(url)) != -1){
imgarr.push(imgels[i]);
}
}
for (var p=0; p< imgarr.length; p++){
if (imgarr[p].parentNode.nodeName=="A"){
imgarres.push(imgarr[p]);
}
}
var z = imgarres[0].src;
return z;
}
function getUrl(){
if (localStorage.id){
var ur = domurl + localStorage.id;
return ur;
}
else {
var notif = webkitNotifications.createNotification(null, 'blah,blah,blah', 'Enter ID in options!!' );
notif.show();
getdata();
}
}
function init() {
getdata();
}
</script>
</head>
<body onload="init();">
</body>
</html>
In options instead of clearTimeout(bg.id1); try bg.clearTimeout(bg.id1);
For image problem looks like you never clean imgarres array, only adding elements to it and then taking the first one.
PS. You code is very hard to read, maybe if you made it well formatted and didn't use cryptic variable names you would be able to find bugs easier.
UPDATE
I think I know what the problem is. When you are setting the timeout you are using local scope variable because of var keyword, so your id1 is visible only inside this function and global id1 is still undefined. So instead of:
var id1 = setTimeout(getdata, 60000*45);
try:
id1 = setTimeout(getdata, 60000*45);
Because of this if(bg.id1){} inside options is never executed.
(bg.clearTimeout(bg.id1); should work after that, but it is not needed as you are clearing the timeout inside getdata() anyway)