How to pass incoming Google Analytics campaign utm strings to outgoing clicks - javascript

I want to have a setup where if I bring traffic to my site by using Google Analytics campaign strings: utm_campaign and utm_source, those strings would be stored and then appended to any outgoing link/click from my site.
Example if I want to bring traffic from a news article in Linkedin
Incoming link:
https://mywebsite.com/landing-page/?utm_campaign=news&utm_source=linkedin
I want it so when a visitor clicks on the outgoing links (or any link in my website), the outgoing link will have the utm string appended like:
https://outgoinglink.com/welcome-aboard/?utm_campaign=news&utm_source=linkedin
Can anyone help how to have something like this.
My website is in Wordpress and there seems no specific plugin for this.

You can do this in Javascript and definitely it would be easier with jQuery, so I will give you jQuery solution.
$(function(){
var params = window.location.search;
if (!!params) {
$('a[href]').each(function(){
$(this).attr('href', $(this).attr('href') + params);
});
}
});
Put this in your header and it will add parameters to your links. Note that this will potentially break your links if they already have query strings attached. In that case this code should have 1 more edge case.
$(function(){
var params = window.location.search;
if (!!params) {
$('a[href]').each(function(){
if ($(this).attr('href').indexOf('?') === -1) {
$(this).attr('href', $(this).attr('href') + params);
} else {
$(this).attr('href', $(this).attr('href') + '&' + params.substr(1));
}
});
}
});
Note that this code is for you to learn, it can be optimised and made more secure for production purposes.
If you need to persist parameters on 2nd or later page, you should first add it to localStorage and then read it from it and append on every link again.
Hope that helps
EDIT:
You can check this pen,
https://codepen.io/mnikolaus/pen/dZeVLv
EDIT 2:
jQuery(function(){
var params = window.location.search;
if (!!params) {
jQuery('a[href]').each(function(){
if (jQuery(this).attr('href').indexOf('?') === -1) {
jQuery(this).attr('href', jQuery(this).attr('href') + params);
} else {
jQuery(this).attr('href', jQuery(this).attr('href') + '&' + params.substr(1));
}
});
}
});

Try this. A client of mind wanted to do the same thing few month ago, I give him this her this and it's working now.
<script type="text/javascript">
(function ($) {
// Get the utm tag from current url
var params = window.location.search;
// if utm available...
if (!!params) {
$('a[href]').each(function(){
// Apply the extracted utms to link
$(this).attr('href', $(this).attr('href') + params);
});
}
}(jQuery));
</script>
It is basically checking for any url without utm tags.
Hope it helps.

Related

How to get current url in jquery

I can't explain myself in title. What i want is get string between slashes. Like that:
www.example.com/foo/bar/id/1
i want to get "foo". Because i made these codes.
select: function(event, ui) {
if(window.location.href = "news/" + ui.item.slug){
window.location.href =null;
}
else
window.location.href ="news/" + ui.item.slug;
}
I have a autocomplete search field. When i clicked a result, its redirecting me to www.example.com/news/34523
In this page if i use search field again, it redirects me to www.example.com/news/news/12412 After that i got 404. But if i am not in news tab, for example www.example.com/foo its working perfecly when i use search field. I just need an if statement, if i am in news pages act like another page.
You could simply use the location.pathname property to get the part between the first and second slash and run code based on this.
console.log(window.location.pathname);
console.log(window.location.pathname.split("/")[1] === "foo");
To show that this works, here is another snippet, acting as if url was window.location:
let url = document.createElement('a');
url.href = "http://www.example.com/foo/bar/id/1";
console.log(url.pathname);
console.log(url.pathname.split("/")[1] === "foo");
The problem seems to be with your url that gets redirected. Try the below code.
select: function(event, ui) {
if(window.location.href = "/news/" + ui.item.slug){
}
else
window.location.href ="/news/" + ui.item.slug;
}

js ecwid url redirect

I have been trying to set up redirects for a range of ecwid urls starting from /shop to /shop#!/~/ to lead to /shop#!/~/cart
I have come up with this code:
var wrong_url = ['http://example.com/shop','http://example.com/shop#','http://example.com/shop#!','http://example.com/shop#!/','http://example.com/shop#!/~','http://example.com/shop#!/~/'];
var current_url = document.URL;
for (i=0;i<wrong_url.length;i++) {
if (current_url==wrong_url[i]) {
document.location.replace('http://example.com/shop#!/~/cart');
break;
}
}
It works all right but there is a problem. When I am at /shop#!/~/cart and then manually change url to, say, /shop#!/~/ it won't get redirected until I refresh the page. I believe this has something to do with ajax behavior of ecwid shopping cart but can't figure out how to fight it.
Need help?
Vitaly from Ecwid here.
The issue in the current version of your script is that it doesn't detect the changes to the URL like you described.
So you will need to create a handler for such situations separately. For example, you can do it like this:
<script>
var wrong_url = ['http://example.com/shop','http://example.com/shop#','http://example.com/shop#!','http://example.com/shop#!/','http://example.com/shop#!/~','http://example.com/shop#!/~/'];
var current_url = document.URL;
// function to check current URL and make a redirect
function checkUrl(){
for (i=0;i<wrong_url.length;i++) {
if (current_url==wrong_url[i]) {
document.location.replace('http://example.com/shop#!/~/cart');
break;
}
}
}
// Execute checkUrl() function each time URL is changed
$(window).bind('hashchange', function() {
checkUrl();
});
// Execute checkUrl() function on initial page load
checkUrl();
</script>

Show content on certain URL

I am using an online store solution which allows me set up a simple online shop. I cannot use any code other than html/css/javascript.
I have put in a simple image-slider in the template. But i want this slider to only be shown on the frontpage. Now its shown on every-page.
Can i use a javascript functions that says something like this: "if url is "www.example.com" then show image-slider else hide it."
Something like this maybe?
<script>
$(function() {
if(document.URL == "http://example.com/") {
...
...
</script>
Thanks on beforehand :)
I don't know the exact circumstances of what you're trying to do it or why you'd need it, but
if (location.href == "http://example.com")
Should do it. Location.href returns the URL of the page, like "document.URL" in your example.
If you're looking to just get certain parts of the URL, this is a really cool tip I found here.
var parser = document.createElement('a');
parser.href = "http://example.com:3000/pathname/?search=test#hash";
parser.hostname; // => "example.com"
parser.pathname; // => "/pathname/"
Essentially what this does is creates a link element in your JavaScript that has properties that return different parts of the URL. This would be relevant if there could be multiple URLs for your index page. For instance, if the user is currently at http://example.com/index#something.
(location.href == "http://example.com/")
Would return false. However, if you did this in your code,
var parser = document.createElement('a');
parser.href = "http://example.com/index#something";
(parser.hostname+parser.pathname == "example.com/index")
That last line would return true for both http://example.com/index and http://example.com/index#something.
Taking the information you've given about the website, here's my best guess as to what your code should look like.
var parser = document.createElement('a');
parser.href = location.href;
if (parser.hostname+parser.pathname != "example.com/index") //If user isn't on the index page
{
$(".slidewrap").hide(); //Hide the div with the class slidewrap
}
window.location is the right area, it exposes a hostname property so you can check just the site name rather than the whole URL, and pathname for just the local path within the site. See https://developer.mozilla.org/en-US/docs/Web/API/Location
So if the home page is http://www.example.com/, then window.locaton.pathname === '/'
i.e.
<script>
$(function() {
if (location.pathname == "/") {
...
}
});
</script>
Im just adding the solution as an answer as i got it to work by mixing j4g and duncans codes:
<script>
$(function() {
if(location.pathname !== "/") {
$("#slidewrap").hide();
}
});
</script>
As i understand it. It says: If location is not index then hide #slidewrap :D And that works perfectly. Thanks.

How do I close the popup after I post to facebook?

On our blog we have a link where users can post our articles to their timeline. A popup opens up and the user posts to facebook, then the popup stays there and redirects to "www.oursite.com". How do we instead close the popup when the user either finishes posting or clicks on the cancel button? According to this so question it can't be done but Huffington post has figured it out but looking at their code we can't figure it out.
As an example, the facebook share button here will open up a popup and then close when you either post the article or cancel.
Here's what we have:
FB.init({appId: "90210", status: true, cookie: true});
function postToFeed() {
// calling the API ...
var obj = {
method: 'feed',
redirect_uri: 'http://www.oursite.com/',
link: 'http://www.oursite.com/',
picture: 'http://www.oursite.com/png.png',
name: 'Some title',
caption: '',
description: ''
};
function callback(response){
window.close(); // doesn't do anything
//document.getElementById('msg').innerHTML = "Post ID: " + response['post_id'];
}
FB.ui(obj, callback);
}
We've tried adding window.close(); in the callback (and also self.close();), tried leaving redirect_uri blank (and tried leaving redirect_uri out altogether, but it's required).
It seems that the accepted answer is no longer working due to the fact that facebook now strips anything after a hash and replaces it with post_id=xxxxx.
Solution #1 (if you trust FB not to change this in the near future):
if(window.location.search.indexOf('post_id')==1) window.close();
Solution #2 (if you want a little more insurance against change and don't mind a second file):
Create a new html file closewindow.html:
<html><body><script>window.close()</script></body></html>
and link to it in the redirect.
Redirect to http://oursite.com/#close_window. Then on your site's homepage, include something like this:
if (window.location.hash == '#close_window') window.close();.
After spending a whole day working on this problem, I have a very good solution that I'd like to share. Instead of using the SDK with FB.ui(), I have discovered that I can avoid it entirely by manually opening my own popup to https://www.facebook.com/dialog/feed. When doing it this way, redirect_uri works as expected. As long as you require the user to click a button to make the dialog pop up, no popup blocker will be triggered.
I don't believe there are any compromises with this code, and if anything, it is much easier to use than the actual SDK.
My Javascript code (which you can save as FacebookFeedDialog.js) looks like this:
/* by Steven Yang, Feb 2015, originally for www.mathscore.com. This code is free for anybody to use as long as you include this comment. */
function FacebookFeedDialog(appID, linkTarget, redirectTarget) {
this.mParams = {
app_id: appID,
link: linkTarget,
redirect_uri: redirectTarget,
display: "popup"
}
};
/* Common params include:
name - the title that appears in bold font
description - the text that appears below the title
picture - complete URL path to the image on the left of the dialog
caption - replaces the link text
*/
FacebookFeedDialog.prototype.addParam = function(key, value) {
this.mParams[key] = value;
};
FacebookFeedDialog.prototype.open = function() {
var url = 'https://www.facebook.com/dialog/feed?' + encodeCGIArgs(this.mParams);
popup(url, 'feedDialog', 700, 400);
};
/* Takes a param object like this:
{ arg1: "value1", arg2: "value2" }
and converts into CGI args like this:
arg1=value1&arg2=value2
The values and args will be properly URI encoded
*/
function encodeCGIArgs(paramObject) {
var result = '';
for (var key in paramObject) {
if (result)
result += '&';
result += encodeURIComponent(key) + '=' + encodeURIComponent(paramObject[key]);
}
return result;
}
function popup(mylink,windowname,width,height) {
if (!window.focus) return;
var href;
if (typeof(mylink) == 'string')
href=mylink;
else
href=mylink.href;
if (!windowname)
windowname='mywindow';
if (!width)
width=600;
if (!height)
height=350;
window.open(href, windowname, 'resizable=yes,width='+width+',height='+height+',scrollbars=yes');
}
Here's a sample HTML file that uses the Javascript code above:
<HTML>
<BODY>
<SCRIPT type="text/javascript" src="FacebookFeedDialog.js"></SCRIPT>
<SCRIPT>
var dialog = new FacebookFeedDialog(yourAppIDGoesHere,yourDestinationURLGoesHere,yourCloseWindowURLGoesHere);
dialog.addParam('name','This is my title');
dialog.addParam('description','This is the description');
dialog.addParam('picture',yourImageURLGoesHere);
dialog.addParam('caption','This is the caption');
</SCRIPT>
Open facebook dialog
</BODY>
</HTML>
Your closeWindow html file can look like this:
<SCRIPT>
window.close();
</SCRIPT>
As of 10/2017 removing redirect_uri seems to work.
It will default to https://www.facebook.com/dialog/return/close#_=_
whose source is just
<script type="text/javascript"> window.close() </script>
UPDATE:
Add this script to your redirect page:
if (document.referrer == "https://www.facebook.com/" && (window.location.href.indexOf('post_id=') != -1 || window.location.hash == '#_=_')) {
window.close();
}
Just remove the redirect_uri parameter from the url.
Like here.
This is not a direct answer to the original question, but it might help others arriving here.
There is a more robust way to do this that allows you take action on the originating page when the share has completed successfully:
In the originating page:
var shareWindow;
function openShareWindow() {
// See https://developers.facebook.com/docs/sharing/reference/share-dialog
shareWindow = window.open('https://www.facebook.com/dialog/share?app_id=...&display=popup&redirect_uri=...');
}
function shareCompleted() {
if (shareWindow) {
shareWindow.close();
shareWindow = null;
// The share was successful, so do something interesting here...
}
}
In the page you have set as your redirect_uri, which I usually map to something like http://myserver.com/share/close:
window.opener.shareCompleted();
Now you're assured the share window will close and you'll be able to take action on the originating page if needed.
Note: shareCompleted must be available in the root window namespace for this work. If you're wrapping all of your JavaScript as you should be, then be sure to:
window.shareCompleted = shareCompleted;
<script>if (window.location.hash.indexOf("#close_window") != -1) window.close();</script>

window.location.hash keeps appending name instead of replacing it when links are clicked

Ok, I have this script working 99% of how it should be working, but I can't seem to figure out this little bit.
When the user clicks on a link it takes the href value and chops it up and gives me the last segment of the url. In this example I'll say its home
so my script then grabs home and adds it to the url in the address bar.
so it look like http://www.site.com/user/s2xi/home after its done doing its magic.
But originally I had an issue where because of the nature of how links work I suppose it would keep appending my url like this http://www.site.com/user/s2xi#/home which on my server doesn't exists
So I was able to get rid of the # and it got everything back to normal...oh wait, no not everything always works perfect on the first try...
so i then realized that my script was appending link names instead of replacing them... oh noes, now what?
my links would now look like this: http://www.site.com/user/s2xi/home/someOtherLink
it would append the new link name to old link name instead of replacing it...
my script:
var newHash = "",
shref = "",
content = '#content',
$c = $("#content"),
$cw = $("#content-wrapper");
$(".menu-link, #my-account-link").live('click', function(){
shref = $(this).attr("href").split("/");
parent.location.hash = $(this).attr("href");
window.location.hash = shref[5];
console.log(window.location.hash);
return false;
});
$(window).bind('hashchange', function(){
if (location.href.indexOf("#") > -1) {
location.assign(location.href.replace(/\/?#/, "/"));
}
newHash = window.location.hash;
//newHash = window.location.hash.substring(1);
//newHash = window.location.substring(1);
//console.log(newHash);
if(newHash)
{
$cw.find(content).fadeOut(200, function() {
$cw.load(newHash + " #content-wrapper", function() {
$c.fadeIn();
});
});
}
});
$(window).trigger('hashchange');
what could be wrong with the script logic?
First, without /.../g, you're just replacing the first match, which may be what you want.
You logic seesm to be:
Replace # with link, so the hash now becomes a link
When you click on a link, the handler takes the last segment in the current href attribute and put it into a hash. Notice that you have not removed that segment from the url.
In other words, say it starts with:
http://www.site.com/user/s2xi
You href, say, is http://www.site.com/user/s2xi/home. Then on your click, you get shref[5] = "home". And you add it to hash of the current url, which makes it:
http://www.site.com/user/s2xi#home
And then you convert that hash back into a link:
http://www.site.com/user/s2xi/home
All is fine. The second time you click on a link, say, http://www.site.com/user/s2xi/foo. On your click, shref[5] = "foo".
You then add it to your hash of the current url:
http://www.site.com/user/s2xi/home#foo
Then you convert that hash back into a link:
http://www.site.com/user/s2xi/home/foo
Voila. You appened the link instead of replacing it. You should be replacing the segment in the url.

Categories

Resources