how to write basic jquery if statement based on url - javascript

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 === ...)

Related

javascript - Getting the iframe's URL after reload of iframe content doesn't work in Chrome and Safari

I'm working on a phaser game that's to be embedded in a website via iframe. The game supports multiple languages, so we've taken to using the site the game was accessed from as an indicator (phaser-game.com/ru would be in Russian, phaser-game.com/ar would be in Arabic, etc).
Here's the code so far (fired via window.addEventListener('load', getDomainSetLanguage);:
function getDomainSetLanguage()
{
let url = (window.location !== window.parent.location) ? document.referrer : document.location.href;
console.log('url = ' + url);
for (let i = 0; i < COUNTRIES_DOMAIN.length; i++)
{
if (url.indexOf(COUNTRIES_DOMAIN[i].URL) >= 0)
{
DOMAIN_ID = COUNTRIES_DOMAIN[i].ID;
LANGUAGE_ID = COUNTRIES_DOMAIN[i].LANGUAGE_ID;
break;
}
}
if (DOMAIN_ID === -1)
{
DOMAIN_ID = 1;
}
if (LANGUAGE_ID === -1)
{
LANGUAGE_ID = 1;
}
console.log('DOMAIN_ID = ' + DOMAIN_ID + "; LANGUAGE_ID = " + LANGUAGE_ID);
}
Now this works fine, on the surface. However, the game does trigger a reload every now and then, and when the game comes back, it now gets it's own URL, not the parent's / iframe's.
This has the result of the game language defaulting to English.
Note that this only occurs in Chrome and Safari. FireFox works just fine.
Is there something I'm missing? Or is there anything else I can try?
I've tried logging the values of document.referrer and document.location.href, but I'm just getting browser errors about permissions and stuff and the game defaults to English.
I read from here that Chrome (and possibly Safari) doesn't fire the onload function of objects in the iframe, but I'm not sure if this applies to me, as I have a lot of other functions tied to onload that do work.
It should be mentioned that I cannot modify the iframe itself, so any solution must be from the game itself.
Thanks!
let url = (window.location !== window.parent.location) ? document.referrer : document.location.href;
This line from your code makes it so that when you're inside of an iframe, document.referrer is used as the URL to determine the language from.
As per the MDN page on Document.referrer:
The Document.referrer property returns the URI of the page that linked to this page.
Inside an <iframe>, the Document.referrer will initially be set to the same value as the href of the parent window's Window.location.
This means it will work on initial load just fine, as you've experienced.
As far as I can tell, the specification isn't explicit about how to handle reloading. This is probably the cause of the differences in browser behaviour. It isn't too crazy to think that is should be empty after a reload, as it wasn't loaded from the parent page that time around.
An alternate solution would be to use window.parent.location.href, which always refers to the URL of the iframe's parent window (read more in Difference between document.referrer and window.parent.location.href).
Your line of code could look something like this:
// if parent and child href are equal, using either yields the same result
// if there is no parent, window.parent will be equal to window
// therefore, the conditional statement isn't necessary
let url = window.parent.location.href;

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.

Window.Location Refreshes instead of Redirects

I have a JQUERY function as follows
this.getURL = function()
{
var name = getName();
alert("Menu.aspx?name"+name);
//window.location = "Menu.aspx?name"+name;
}
When I alert the URL I am attempting to go to, it is correct. However, when I call window.location on that string, the page just refreshes without going anywhere.
I have similar code where I have used window.location and it works. I typed in the url into my browser and it works as well.
At worst (even if the URL was wrong), I was hoping that it would just redirect me to some URL. However, I can't get it to do anything other than refresh the current page.
Also to clarify, the page which calls this function is not Menu.aspx
Thanks in advance.
If you're using a relative path try setting window.location.pathname, otherwise set window.location.href for a full path.
You may also want to try self.location.href
In my experience, it's been difficult to get redirects like this to work right. I've had to use window.location.replace(<url>). If you're just changing an anchor tag, it's even more difficult. You have to do the following to get it to work in all browsers:
window.location.replace(<url>);
window.location=<url>;
window.open(<url>,'_self');
window.location.reload();

Check if window.history.go successful?

Is there anyway to check if a window.history.go command is successful in changing the window.location or not?
i.e. If I do a window.history.go(-5) when there are only 3 pages in the history stack, the browser will do nothing.
Is there a way to check if that happens and run other code? An error callback, of sorts.
Thanks.
For an immediate response, first you'll want to check history.length to make sure it is at least 6, e.g. to go -5. Apart from that, I think the only way is to use setTimeout and if the script is still running, the callback will be executed.
Not really a JS expert, but if you want to perform some action when the user goes back or forward, you could use URL hashes and trigger some function using the jQuery onhashchange event. This will not give you the position in history, and i'm also not sure about cross-browser compatibility, but it did the job for me so far.
$(window).on('load' function(){
var hash = parent.top.location.hash;
if(hash == '' || hash == '#' || hash == null){
//if none, set a hash and reload page
parent.top.location.hash = '#/some/hash';
parent.top.location.reload(true);//use true if you dont want to use cached items
}
});
$(window).on('hashchange', function(){
do_something(parent.top.location.hash);
});
function do_something(hash){
//this function will be executed each time the '#' changes
console.log('hash changed to '+hash);
}

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

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!");
}

Categories

Resources