Pull links from incoming visitors (referrals) via Javascript or jQuery - javascript

Is there a way to pull links from incoming visitors on a page (referrals)? I essentially want to do some if statements.
if user is from Nextag.com {do some javacode} else from Pricegrabber.com {do some javacode}.
Before I can do the if statements I need to find out how that user got on our page (where did they come from). I know google analytics does this but is there a way to hard code it on one page so I can do the above?

You can get the referer URL with document.referrer, it is supported cross-browser.
It might not be set though based on the user's privacy preferences, firewall, etc. Some proxies also clear or fake it.
You can run some Regexes on the value or use indexOf, and do some actions based on them.
For example (not final code):
if (document.referrer.indexOf('nextag.com') != -1) {
//user came from nextag.com
}
MDC Docs on document.referrer

You can use document.referrer (assuming it is populated by the user's browser).

Use the document.referrer property to get the originating URL, plus some basic pattern matching for validation:
var reURL = new RegExp("^https?:\/\/(www.)?nextag.com\/", "i");
if (document.referrer.length && reURL.test(document.referrer)) {
alert("Hello, nextag.com!");
} else {
alert("Hello, world!");
}

Related

Filter Link Tracking issue in Adobe DTM

I am facing issue with adobe image request in network tab, I can proper see results in console, but while in image request I am not seeing Evar55 current value.
Actually there is bug Analytics tracking issue- Evar55
Evar55 should capture the value of filter selected by users on search result page and PLP.
So now the next thing I have written the code, which is working absolutely fine in Console, and I can see the result but in network tab the image request is giving previous value not giving the current value of facet.
Here I am sharing the screenshot and code with you, please tell what issue is.
In DTM, I have created page load rule – conditions trigger rule at DOM ready –then adobe analytics open editor I have pasted this code
Code
var oldXHR = window.XMLHttpRequest;
function newXHR() {
var realXHR = new oldXHR();
realXHR.addEventListener("readystatechange", function() {
if(realXHR.readyState==4 && realXHR.status==200){
//run your code here
window.setTimeout(function() {
if(s.pageName && (s.pageName.indexOf('plp:')>-1 || s.pageName.indexOf('search')>-1)){
var PFF = document.getElementsByClassName('selected-categories')[0].innerText;
PFF_Final = PFF.replace(/ /g, '').replace(/:/g, '|');
if(PFF_Final.indexOf('Categories|')>-1 || PFF_Final.indexOf('search|')>-1){
console.log('N/A');
}
else if(PFF_Final && typeof PFF_Final !== 'undefined' && PFF !== 'null' && PFF !== ''){
//PFF_Final = PFF.replace(/ /g, '').replace(/:/g, '|');
s.linkTrackVars = 'eVar91';
s.eVar91 = PFF_Final.trim();
//s.tl(this, 'o');
console.log(PFF_Final);
}
}
},1500);
}
}, false);
return realXHR;
}
window.XMLHttpRequest = newXHR;
Note : - I have change the Evar55 to Evar91 because Evar 55 which is already in use.
enter image description here
enter image description here
Thanks,
Payal
At face value, the immediate reason the code you posted does not make a request because you have the s.tl call commented out...
Second, a note: if you are filtering for image requests in the network tab, you will almost certainly not see the Adobe Analytics (AA) request there, because unless you are using a very ancient browser or else have javascript turned off and using the <img> tag method, it will show up as either a javascript request or ajax (xhr) request (depending on what version of the AA library and how long the request is).
If you are still not seeing the request, there are a couple additional things to try. One or more of these may or may not be true/necessary, depending on what version of the AA library you are using:
1) When you pass this as the first argument, it must be a valid anchor element with an href attribute <a href='..'></a>. Since this is not applicable within the context of your posted code, try changing the first argument to boolean true.
2) Add a 3rd argument to the s.tl call. This argument is supposed to be a description for the link click, e.g. s.tl(true,'o','some link'); It can be anything you want; it's what shows up in the native link reports in AA (that you will almost certainly ignore, in favor of looking at that eVar91 report, instead). All versions of the AA library require this 3rd argument if you want to track it as a click/interaction server call. Without it, in more recent versions of AA, it will trigger the request as a page view call, but in older versions of the AA library, it will not trigger a call at all.
3) Again, depending on your AA lib version, it will not include anything above eVar75. I don't remember the exact AA version where eVar76+ was introduced (edit: Looks like Starting AM1.4. Legacy H code not supported). As a quick check, try using eVar75 or lower to see if it shows up in the request. Note: I'm only putting this for completeness sake, but I don't think this your issue, since it seems from your post you may have tried with eVar55 already? But may as well be certain. If this is the case, I would suggest updating to the latest AppMeasurement library. If for some reason you are unable to do that, and still need to use eVar91, then the alternative is to pop it as a contextData variable, e.g. s.contextData['eVar91']='foo'; and then map it to the real eVar91 in a Processing Rule within the AA interface. If your AA library is old enough that even contextData variables don't work (H23.2 or lower).. then I suggest you make it your highest priority in life to upgrade to a more recent version of the AA lib..
If after all of this you still do not see an AA call, just type s.t(true,'o','foo'); into the js console. Do you see an http request? If you do not see a request, then you have some deeper issue not directly related to the posted code. Perhaps your AA library is not present, or it is not loaded before this is triggered, or is under a different namespace than the default s namespace. But it's not really feasible to write lots of random guesses here vs. looking at the site.
If you do see a request, then my best guess at this point is you having a timing issue. Perhaps there is a page (re)load happening and it is not getting a chance to trigger? But again, it's not very feasible to speculate on a site unseen.

How do i make a redirect a iPad user?

This has probably been answered before but i don't understand al the difficult research online so i ask it here And hope for a easy answer
<script type="text/javascript"> // <![CDATA[
if ((navigator.userAgent.indexOf('iPad') != -1)) {
location.replace = "http://www.joey-games.byethost4.com/games/";
} // ]]>
This does not redirect me.
var isiPad = navigator.userAgent.match(/iPad/i) != null;
//or by using
var ua = navigator.userAgent;
var isiPad = /iPad/i.test(ua)
You can find other related information in the following links:
http://fellowtuts.com/jquery/ipadiphone-detection-using-javascript/
Detect iPad users using jQuery?
Instead of using location.replace use location.href
Your snippet becomes
if (navigator.userAgent.indexOf('iPad') > -1) {
location.href = 'http://www.joey-games.byethost4.com/games/';
}
I've made two changes to your code
!= to > in the if statement which is no biggie (nothing relevant)
changed method call from replace to href Taken from MDN
The Location.replace() method replaces the current resource with the one at the provided URL. The difference from the assign() method is that after using replace() the current page will not be saved in session History, meaning the user won't be able to use the back button to navigate to it.
This basically says that if you use replace you cannot use the browsers back button to get to this page anymore, basically reducing the users user-experience since they'll get confused about what the back button does when they use your website.
This will redirect your users on the iPad to a different website however, you shouldn't do this - it's bad for your users and your website. (as partially explained above)
Iam Not gonna use The redirecting to go to "Joey-games.byethost4.com/games/" I wil redirect iPad users to: Joey-games.byethost4.com/mobile/iPad/ for a mobile site since flash player is not supported in safari yet

Getting Backbutton to work in single page website and implementing "speaking" URLs

I have a single page website and would like to achieve the following:
back button working as if it was a normal website
and instead of say,
www.mysite.com/index.php?p=#this-is-a-great-product
I'd like to have this url
www.mysite.com/this-is-a-great-product
while still having back button working properly.
Regarding 1.) I use the following code ive found which works great:
<!-- Getting BackButton to work properly -->
<script type="text/javascript">
var times = 0;
function doclick() {
times++;
}
function doclick() {
times++;
location.hash = times;
}
window.onhashchange = function() {
if (location.hash.length > 0) {
times = parseInt(location.hash.replace('#',''),10);
} else {
times = 0;
}
}
</script>
…but of course it just changes any anchors to /#1, then /#2 and so forth ro get the backbutton to work. But as I'm not a programmer I don't know how to change it… :(
Regarding 2.) i can add in htaccess this:
>RewriteEngine On
>RewriteRule ^([^/.]+)/?$ /index.php?page=$1
and this changes /index.php?p=products to /products.
So how do I change the above code (under 1.) so it doesn't change all anchors to #1, #2, etc. but instead references / uses the urls I achieved under 2, like
www.mysite.com/this-is-a-great-product
And (probably a very dumb question, but a very important one) -given I use only the new url links on my site- is there any danger that this still might result in duplicate content in any way?
Regarding this, should I (for that reason or any other) sefreferential my single page index.php to itself using rel canonical link=index.php?
Thanks so much in advance!
As mentioned, you will want to use the HTML5 History API. Please note, this API is relatively new and therefore browser support is a concern. At the time of writing, approximately 71% of global Internet users have support for it (see http://caniuse.com/#feat=history for browser support information). Therefore, you will want to ensure you have a fall-back solution for this. You will likely want to use the older #! solution that was popular before the HTML 5 History API was adopted.
If you use the history API to replace, for example, example.com/#!settings with example.com/settings and a user bookmarks that nicer URL, then when they go to visit it, their browser will make a request to the server for /settings (which doesn't actually exist in the web server's context). Therefore, you will need to make sure your web server has some redirection rules (i.e. RewriteEngine) such that it can take the pretty URLs and redirect them to the #! version (and then if the user's browser supports the history API it can replace that with the nice URL).
If you aren't very comfortable programming yourself, I'd recommend using a JavaScript library that does a lot of the work for you. I did some quick searching and discovered the following, though there might be better ones out there: https://github.com/browserstate/history.js
Basically i have created a small prototype on jsfiddle which tracks all the urls accessed via ajax calls.
Also contains navigation to access links back and forth .
How It Actually Works:
I have created a global array called history, which keeps track of all urls accessed via ajax in sequence.
also there a global index defined to keep track of the url being accessed when navigating back and forth the links in history array.
There is History section at the bottom of the jsfiddle, which shows the sequence in which the links are accessed by capturing the link names and posting them in the order in which they were accessed.
JS Code:
$(function () {
var history = [];
var index = 0;
$('.links').on('click', function () {
$('#history').append($(this).text());
var address = $(this).attr('data-ref');
index += 1;
history[index] = address;
$('.links').attr('disabled', 'disabled');
loadExternalPage(address);
console.log('list:' + history);
});
$('#back').on('click', function () {
console.log(index);
index -= 1;
console.log(index);
console.log(history[index]);
loadExternalPage(history[index]);
});
$('#forward').on('click', function () {
console.log(index);
index += 1;
console.log(index);
console.log(history[index]);
loadExternalPage(history[index]);
});
var loadExternalPage = function (address) {
console.log(history[index]);
$('#result-section').load(address, function () {
console.log('data-loaded');
$('.links').removeAttr('disabled');
});
};
});
Live Demo # JSFiddle:http://jsfiddle.net/dreamweiver/dpwmcu0b/8/
Note: This solution is far from being perfect, so dont consider it as final solution but rather use it as a base to build upon
On using BACK and FORWARD functions in the browser top-left button:
In principle, there is no great problem with this as long as you work with the existing storage object (a stack) for previously visited web pages on your browser. This object is the history object and you can see what is in it anytime by right-clicking and selecting "Inspect", then selecting the "Console" tab, then enter window.history and enter.
Check out the Browser Object Model (BOM) section of Pro Java For Web Developers (Frisbee) for the background to the history object. (Just a few pages, an easy read, don't worry.) Just remember that in this process you are storing the new page that you move to, not the old page that you are leaving !
For a simple SPA example, look at this example. codepen.io/tamjk/pen/NWxWOxL
In regard to the URL, the method that the history object uses to load a new page state into the history stack, i.e. pushState(...), has an optional third parameter for associating a dummy URL for each web page that is stored.
Personally, when I first sorted out the BACK & FORWARD functions, I did not use dummy URLs as the browser was being confused by them and I had enough to do sorting out the history sequence using just the first two parameters, i.e.
the state object - a JSON holding enough data to recreate the page stored
a title for the page I expect that you could also use a dummy URL but I will leave that to the student as an exercise, as they say.
But you can add the URL of the new page if you want to.
In the example above, for the state object I just used the IDs of the page's nav link and its content element.
For the title, I programmatically changed the HTML's page title element with each change of page. I did this after noticing that the browser listed the previous pages according to the title element in the HTML code.
Unfortunately, this title does not show up on CodePen when you right-click on the browser BACK and FORWARD buttons due to CodePen's system not allowing it. But it will show on your own sites.
It's important that whatever method you use to store current web page states when using the navbar links to navigate, you DO NOT ADD page states to the browser history when you arrive at them using BACK or FORWARD buttons. Otherwise your history stack will have repetitions of entries going back and deletion of entries going forward.
In the CodePen, this was achieved by having the addToHistory(..) function separate to and outside the scope of the switchPage(...) function. This allows you use of the switchPage function in both normal navbar navigation and browser BACK/FORWARD navigation. The third parameter of switchPage(...) is a boolean indicating if the page is to be stored in history or not.
Anyway, this is just something to get you started.

Redirect users who already accepted terms to another webpage (cookies or localStorage)

I ve made a mobile version of a website. Before the user see a specific page he must press a button - CONFIRM, which basically confirms that he accepts the terms of our website. Moreover, as soon as the user press the CONFIRM button he is being redirected to the specific page.
My question is how is it possible to use cookies or localStorage in order to redirect the users who already had been accepted the terms to the specific web page?
I am not quite programming savvy so please be nice :)
You can check like this:
if (localStorage.getItem('accepted') === '1') {
//redirect - already accepted;
}
// after clicking accept
if (accepted === true) {
localStorage.setItem('accepted', '1');
//redirect
}
Note that the check and set must be in the same origin.
Demo:
http://jsfiddle.net/AbdiasSoftware/wk9bS/
Of course, you'll need to check that localStorage is available (implicit IMO) and provide a fallback mechanism such as persistent cookies:
if (!!window.localStorage) {
//use code above
} else {
//use fallback
}

how to write basic jquery if statement based on url

I don't know why this doesnt work. Although im sure its something to do with the way im handling the url in the if statement. My Jquery / javascript knowledge if basic.
var url = $(location).attr('href');
if (url == 'http://www.website.com/test/index.html')
{
$('#HomeButton').bind('click', HomeButton);
}
function HomeButton(e) {
e.preventDefault();
doSomething....
};
Don't use jquery to access standard object properties.
You can do
if (document.location.href == 'http://www.website.com/test/index.html')
but you should never compare to the whole URL : you'd have wrong result if you change your domain, test elsewhere, use https, add a parameter, etc. You should use the intended property of location, that is pathname :
if (document.location.pathname == '/test/index.html')
In case of doubt, if you want to be sure of your pathname, simply open Chrome's developer tools (by typing F12) and type this on the console : document.location.pathname.
window.location isn't a a DOM element so you can't use jQuery methods on it.
The .href is actually a property of a Location object.
Just use it direct - if (window.location.href === ...)

Categories

Resources