How to put marchex call tracking script within conditions? - javascript

I have to put the marchex call tracking script in the footer section of the site only if cookie is set,but the site is in square space and i can only use javascript/jquery . I have tried the following code but it seems not triggering, means the number changing is not working.
<script>
window.onload = function () {
if(getCookiee("cpc")!="1" && getCookiee("fb")!="1" )
{
vs_account_id = "xxxxxxxxxx";
var s = document.createElement("script");
s.type = "text/javascript";
s.src = "https://rw1.marchex.io/euinc/number-changer.js";
$("body").append(s);
}
}
</script>
The actual script is :
<script type="text/javascript"><!--
vs_account_id = "xxxxxxxx";
//--></script>
<script type="text/javascript" src="https://rw1.marchex.io/euinc/number-changer.js">
</script>
Thank You

My solution is:
var vs_account_id = "xxxxxxxxxx";
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 '';
}
window.addEventListener('load', function() {
if(getCookie("cpc") != '' && getCookie('fb') != '') {
var body = document.getElementsByTagName('body')[0];
var s = document.createElement("script");
s.type = "text/javascript";
s.src = "https://rw1.marchex.io/euinc/number-changer.js";
body.append(s);
}
});
It is vanilla javascript without jQuery.

Related

Append javascript function to div

I need to add the following code to the footer of my page, but I have to do it using javascript code.
Code I need to add:
<script type="text/javascript">
(function (d, w, c) {
(w[c] = w[c] || []).push(function() {
try {
w.yaCounter39519115 = new Ya.Metrika({
id:39519115,
clickmap:true,
trackLinks:true,
accurateTrackBounce:true
});
} catch(e) { }
});
var n = d.getElementsByTagName("script")[0],
s = d.createElement("script"),
f = function () { n.parentNode.insertBefore(s, n); };
s.type = "text/javascript";
s.async = true;
s.src = "https://mc.yandex.ru/metrika/watch.js";
if (w.opera == "[object Opera]") {
d.addEventListener("DOMContentLoaded", f, false);
} else { f(); }
})(document, window, "yandex_metrika_callbacks");
What I tried to add:
$('#footer').append('<script type="text/javascript">' + (function (d, w,.... + '</script>');
However, this does not work for me.
Place your javascript in a separate .js file and then you need to use the document.createElement method to add/append your script to your footer block.
Try the below snippet.
var scriptSource = document.createElement('script');
var scriptURL = 'your_script_file_url_goes_here';
scriptSource.type = 'text/javascript';
scriptSource.src = scriptURL ;
$("#footer").append(scriptSource);
Hope this helps!.

Disqus in Ionic APP

I am trying to implement disqus commments in my ionic app. I know I have to host it on the domain its setup for which I believe I have configured correctly. Any assistance will be welcomed
Here is the code in my app.js for the ionic app
$scope.showComments = function () {
$scope.currentView = "comments";
//loadComments(params["shortname"], params["url"], params["title"], params["identifier"]);
//
var disqus_title = "Venue 1";
var disqus_identifier = '/venue/' + $stateParams.id;
var disqus_url = 'liverpool.li/venue/' + $stateParams.id;
var url = "http://liverpool.li/app/disqus.html?";
$scope.url = url + "shortname=liverpoolli&url=" + encodeURIComponent(disqus_url) +
"&title=" + encodeURIComponent(disqus_title) + "&identifier=" + encodeURIComponent(disqus_identifier);
$scope.url = $sce.trustAsResourceUrl($scope.url);
};
$scope.$on("$destroy", function () {
if ($scope.lastScriptElm && $scope.lastScriptElm.parentNode) {
$scope.lastScriptElm.parentNode.removeChild($scope.lastScriptElm);
$scope.lastScriptElm = null;
}
});
And the page it points to (disqus.html) located on my domain
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
</head>
<body>
<div id="disqus_thread"></div>
<script type="text/javascript">
var params;
var disqus_url;
var disqus_title;
var disqus_shortname;
var disqus_identifier;
window.onload = function () {
var match,
pattern = /\+/g,
search = /([^&=]+)=?([^&]*)/g,
decode = function (s) { return decodeURIComponent(s.replace(pattern, " ")); },
query = window.location.search.substring(1);
params = {};
while (match = search.exec(query))
params[decode(match[1])] = decode(match[2]);
if (params["shortname"] === undefined || params["url"] === undefined || params["title"] === undefined) {
alert("Required arguments missing");
}
else {
loadComments(params["shortname"], params["url"], params["title"], params["identifier"]);
}
};
function loadComments(shortname, url, title, identifier) {
disqus_url = url;
disqus_title = title;
disqus_shortname = shortname;
if (identifier !== undefined)
disqus_identifier = identifier;
else
disqus_identifier = "";
(function() {
var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = false;
dsq.src = 'http://' + disqus_shortname + '.disqus.com/embed.js';
(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
})();
}
</script>
<noscript>Please enable JavaScript to view the comments powered by Disqus.</noscript>
blog comments powered by <span class="logo-disqus">Disqus</span>
</body>
</html>
I get the following error
we were unable to load disqus. if you are a moderator please see our
troubleshooting guide.
It looks like you're almost there. The only issue I see is the disqus_url variable must also include the protocol to be valid. Try using this line instead:
var disqus_url = 'http://liverpool.li/venue/' + $stateParams.id;

JavaScript: "Syntax error missing } after function body"

Ok, so you know the error, but why on earth am I getting it?
I get no errors at all when this is run locally, but when I uploaded my project I got this annoying syntax error. I've checked the Firebug error console, which doesn't help, because it put all my source on the same line, and I've parsed it through Lint which didn't seem to find the problem either - I just ended up formatting my braces differently in a way that I hate; on the same line as the statement, bleugh.
function ToServer(cmd, data) {
var xmlObj = new XMLHttpRequest();
xmlObj.open('POST', 'handler.php', true);
xmlObj.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xmlObj.send(cmd + data);
xmlObj.onreadystatechange = function() {
if(xmlObj.readyState === 4 && xmlObj.status === 200) {
if(cmd == 'cmd=push') {
document.getElementById('pushResponse').innerHTML = xmlObj.responseText;
}
if(cmd == 'cmd=pop') {
document.getElementById('messages').innerHTML += xmlObj.responseText;
}
if(cmd == 'cmd=login') {
if(xmlObj.responseText == 'OK') {
self.location = 'index.php';
}
else {
document.getElementById('response').innerHTML = xmlObj.responseText;
}
}
}
}
}
function Login() {
// Grab username and password for login
var uName = document.getElementById('uNameBox').value;
var pWord = document.getElementById('pWordBox').value;
ToServer('cmd=login', '&uName=' + uName + '&pWord=' + pWord);
}
// Start checking of messages every second
window.onload = function() {
if(getUrlVars()['to'] != null) {
setInterval(GetMessages(), 1000);
}
}
function Chat() {
// Get username from recipient box
var user = document.getElementById('recipient').value;
self.location = 'index.php?to=' + user;
}
function SendMessage() {
// Grab message from text box
var from = readCookie('privateChat');
var to = getUrlVars()['to'];
var msg = document.getElementById('msgBox').value;
ToServer('cmd=push','&from=' + from + '&to=' + to + '&msg=' + msg);
// Reset the input box
document.getElementById('msgBox').value = "";
}
function GetMessages() {
// Grab account hash from auth cookie
var aHash = readCookie('privateChat');
var to = getUrlVars()['to'];
ToServer('cmd=pop','&account=' + aHash + '&to=' + to);
var textArea = document.getElementById('messages');
textArea.scrollTop = textArea.scrollHeight;
}
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;
}
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
vars[key] = value;
});
return vars;
}
The problem is your script on your server is in one line, and you have comments in it. The code after // will be considered as comment. That's the reason.
function ToServer(cmd, data) { var xmlObj = new XMLHttpRequest(); xmlObj.open('POST', 'handler.php', true); xmlObj.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); xmlObj.send(cmd + data); xmlObj.onreadystatechange = function() { if(xmlObj.readyState === 4 && xmlObj.status === 200) { if(cmd == 'cmd=push') { document.getElementById('pushResponse').innerHTML = xmlObj.responseText; } if(cmd == 'cmd=pop') { document.getElementById('messages').innerHTML += xmlObj.responseText; } if(cmd == 'cmd=login') { if(xmlObj.responseText == 'OK') { self.location = 'index.php'; } else { document.getElementById('response').innerHTML = xmlObj.responseText; } } } };}function Login() { // Grab username and password for login var uName = document.getElementById('uNameBox').value; var pWord = document.getElementById('pWordBox').value; ToServer('cmd=login', '&uName=' + uName + '&pWord=' + pWord);}// Start checking of messages every secondwindow.onload = function() { if(getUrlVars()['to'] != null) { setInterval(GetMessages(), 1000); }}function Chat() { // Get username from recipient box var user = document.getElementById('recipient').value; self.location = 'index.php?to=' + user;}function SendMessage() { // Grab message from text box var from = readCookie('privateChat'); var to = getUrlVars()['to']; var msg = document.getElementById('msgBox').value; ToServer('cmd=push','&from=' + from + '&to=' + to + '&msg=' + msg); // Reset the input box document.getElementById('msgBox').value = "";}function GetMessages() { // Grab account hash from auth cookie var aHash = readCookie('privateChat'); var to = getUrlVars()['to']; ToServer('cmd=pop','&account=' + aHash + '&to=' + to); var textArea = document.getElementById('messages'); textArea.scrollTop = textArea.scrollHeight;}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;}function getUrlVars() { var vars = {}; var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) { vars[key] = value; }); return vars;}
You're missing a semi-colon:
function ToServer(cmd, data) {
var xmlObj = new XMLHttpRequest();
xmlObj.open('POST', 'handler.php', true);
xmlObj.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xmlObj.send(cmd + data);
xmlObj.onreadystatechange = function() {
if(xmlObj.readyState === 4 && xmlObj.status === 200) {
if(cmd == 'cmd=push') {
document.getElementById('pushResponse').innerHTML = xmlObj.responseText;
}
if(cmd == 'cmd=pop') {
document.getElementById('messages').innerHTML += xmlObj.responseText;
}
if(cmd == 'cmd=login') {
if(xmlObj.responseText == 'OK') {
self.location = 'index.php';
}
else {
document.getElementById('response').innerHTML = xmlObj.responseText;
}
}
}
}; //<-- Love the semi
}
Additional missing semi-colon:
// Start checking of messages every second
window.onload = function() {
if (getUrlVars()['to'] != null) {
setInterval(GetMessages(), 1000);
}
}; //<-- Love this semi too!
I think you can adapt divide and conquer methodology here. Remove last half of your script and see whether the error is coming. If not, remove the first portion and see. This is a technique which I follow when I get an issue like this. Once you find the half with the error then subdivide that half further till you pin point the location of the error.
This will help us to identify the actual point of error.
I do not see any problem with this script.
This may not be the exact solution you want, but it is a way to locate and fix your problem.
It looks like it's being interpreted as being all on one line. See the same results in Fiddler 2.
This problem could do due to your JavaScript code having comments being minified. If so and you want to keep your comments, then try changing your comments - for example, from this:
// Reset the input box
...to...
/* Reset the input box */
Adding a note: very strangely this error was there very randomly, with everything working fine.
Syntax error missing } after function body | At line 0 of index.html
It appears that I use /**/ and //🜛 with some fancy Unicode character in different parts of my scripts for different comments.
This is useful to me, for clarity and for parsing.
But if this Unicode character and probably some others are used on a JavaScript file in comments before any JavaScript execution, the error was spawning randomly.
This might be linked to the fact that JavaScript files aren't UTF-8 before being called and read by the parent page. It is UTF-8 when the DOM is ready. I can't tell.
It seems there should be added another semicolon in the following code too:
// Start checking of messages every second
window.onload = function() {
if(getUrlVars()['to'] != null) {
setInterval(GetMessages(), 1000);
}
}; <---- Semicolon added
Also here in this code, define the var top of the function
function readCookie(name) {
var i;
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(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;
}
"Hm I think I found a clue... I'm using Notepad++ and have until recently used my cPanel file manager to upload my files. Everything was fine until I used FireZilla FTP client. I'm assuming the FTP client is changing the format or encoding of my JS and PHP files. – "
I believe this was your problem (you probably solved it already). I just tried a different FTP client after running into this stupid bug, and it worked flawlessly. I'm assuming the code I used (which was written by a different developer) also is not closing the comments correctly as well.

Reading cookie data and redirecting

I need some help with reading cookies. My website is bilingual, and as I do not want to change language based on IP, I need to be able to set a cookie which I'll call '_lang' and see if the contents are 'en' or 'jp'. I can set the cookie and its contents, no problems, but I can't work out the syntax for reading cookie contents; this is the first time I've actually tried it.
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=/";
}
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;
}
function GetCookie(name) {
var arg=name+"=";
var alen=arg.length;
var clen=document.cookie.length;
var i=0;
while (i<clen) {
var j=i+alen;
if (document.cookie.substring(i,j)==arg)
return "here";
i=document.cookie.indexOf(" ",i)+1;
if (i==0) break;
}
return null;
}
var visit=getCookie("_lang");
var rc=readCookie("_lang");
if (visit==true){
if (rc == "jp"){
window.location = "http://jp.mywebsite.com";
}
else if (rc == "en"){
window.location = "http://www.mywebsite.com";
}
}
else if (visit==null){
document.title = "Welcome to MyWebsite!"
document.getElementById('welcomeLB').style.display='block';
document.getElementById('behindLightBox').style.display='block';
}
I would recommend to use plugin. https://github.com/pavelkukov/localdata
in your case:
var lang_cookie = readCookie('user_lang') ;
if( lang_cookie && lang_cookie !== null && lang_cookie !== 'undefined')
{
if(lang_cookie === 'en')
{
document.location = 'http://en.mysite.com';
}
document.location = 'http://jp.mysite.com';
}
document.location = 'http://en.mysite.com';

JS get and insert into <script>

I'm writing this code for an extension but It returns:
Origin chrome-extension://gjganecebobheilkbpmhmocibjckgidc is not allowed by Access-Control-Allow-Origin
var randomstring = '';var jsid = 0;
for (var i=0; i<20; i++) {
var rnum = Math.floor(Math.random() * "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz".length);
randomstring += "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz".substring(rnum,rnum+1);
}
function addS(file){
var xmlHttp = null;
xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET", file, false );
xmlHttp.send( null );
jsid = jsid + 1;
var s = document.createElement('script');
s.type = 'text/javascript';
// s.src = file;
s.innerHTML = xmlHttp.responseText;
s.async = "true";
s.id = randomstring+"_unique"+jsid;
s.className = randomstring;
document.head.appendChild(s);
}
addS('https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js');
addS('http://domain.com/functions.js'');
I would use jQuery but I can't because it breaks the source code of the page, what I want is to do the same as this, but in javascript and skipping that error
function addS(file){
jsid = jsid + 1;
$.get(file, function(data) {
var string = '<script type="text/javascript" async="true" id="'+randomstring+"_unique"+jsid+'" class="'+randomstring+'">'+data+'</script>';
$('head').append(string);
});
Additional Info
I'm gonna insert jquery.js and functions.js with an ID like this tags:
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" async="true" id="AWhAXksocT6o6OrBxT28_unique1" class="AWhAXksocT6o6OrBxT28"></script>
<script type="text/javascript" src="http://domain.com/functions.js" async="true" id="AWhAXksocT6o6OrBxT28_unique2" class="AWhAXksocT6o6OrBxT28"></script>
with this code:
function addS(file){
jsid = jsid + 1;
var s = document.createElement('script');
s.type = 'text/javascript';
s.src = file;
s.async = true;
s.id = randomstring+"_unique"+jsid;
s.className = randomstring;
document.head.appendChild(s);
}
I need this ID (via var randomstring) to keep alive, that's the main problem because I will need to delete both after function ends but it returns
functions.js: Uncaught ReferenceError: randomstring is not defined using this code
$(document).ready(function(){
alert("Functions loaded");
//Do some functions....
$("."+randomstring).delete();
});
Thanks!
You can't perform a cross-domain ajax request unless the domain you are requesting from implements CORS.
What you are doing currently IS a cross-domain ajax request. If you instead do as Sirko suggested and request it by making the src of the script element you are appending the url to the ajax request, it will properly make the request.
function addS(file){
//var xmlHttp = null;
//xmlHttp = new XMLHttpRequest();
//xmlHttp.open( "GET", file, false );
//xmlHttp.send( null );
//jsid = jsid + 1;
var s = document.createElement('script');
s.type = 'text/javascript';
s.src = file;
//s.innerHTML = xmlHttp.responseText;
s.async = "true";
s.id = randomstring+"_unique"+jsid;
s.className = randomstring;
document.head.appendChild(s);
}
What is the purpose of this function? In what context is it used? What does it accomplish?
As far as I can see, you're just pasting the content of a file into the script tag.
So why not pass the file url directly to the src parameter of the script tag instead?
function addS( file ) {
var scriptEl = document.createElement( 'script' );
scriptEl.setAttribute( 'src', file ) ;
document.head.appenChild( scriptEl );
}

Categories