Check if homepage using window.location - javascript

Is it possible to check if I'm on the homepahge/index of a site using window.location?
I'm currently checking url using
window.location.href.indexOf("/category/something")
but how can I check for homepage? It doesn't contain any segments.
Note: I don't know what the homepage URL will be so I can't use for example a url name like window.location.href.indexOf("myhomepage.html")
Update: The only clue that I have is that the homepage has no URL segments.

The term homepage itself is a fairly vague construct and not something that is technically identifiable. You could have several different landing pages depending on your screen size, device, credentials, browser, date/time, geolocation, etc. etc.
The only way you can ensure you are on one of these landing pages is to be in control during the initial GET request to the domain (e.g. http://www.example.com).
So, if you're already on the page, there's no real way to know how you got there and if this is the default page provided from that domain, though there are hacks you could try to get a general (albeit very error-prone) idea.
For example, you could compile a list of common homepage paths:
var homepages = [ '/', 'index.html', 'index.htm', 'index.php', 'main.html', 'main.htm', 'homepage.html', 'index2.htm' ];
Then compare to the provided window.location.pathname:
if (homepages.indexOf(window.location.pathname) >= 0) {
// we might be on a "homepage"
}

Many site's homepage, including stackoverflow contain a link to that same homepage.
// browser url = http://example.com
my site
If you have access to the source, you can identify this link server-side
<a id="homepage" href="http://example.com"/>my site</a>
So, to check if you are on the homepage:
document.addEventListener('DOMContentLoaded', function(e) {
var link = document.querySelector('#homepage');
if (link.href == window.location.href) {
//i'm on the homepage
}
})
So i just saw your update to the question. if you know there are no url segments, wouldn't window.location.pathname always be "/"

If you simply did window.location and checked the args in there, if there are no pages/paths appended, url matches origin, etc., would that not be good enough to detect -- Idk, I've never had a need to do this? This might also work for .NET and 'other' types of HTML naming conventions (i.e. index.html vs index.htm). Additionally, if someone changes the doc root, or a home page pointer, you'd more or less know (aka not care) because window.location you can check the following:
window.location
Location {replace: function, assign: function, ancestorOrigins: DOMStringList, origin: "http://stackoverflow.com", hash: ""…}ancestorOrigins: DOMStringListassign: function () { [native code] }hash: ""host: "stackoverflow.com"hostname: "stackoverflow.com"href: "http://stackoverflow.com/"origin: "http://stackoverflow.com"pathname: "/"port: ""protocol: "http:"reload: function reload() { [native code] }replace: function () { [native code] }search: ""toString: function toString() { [native code] }valueOf: function valueOf() { [native code] }__proto__: Location
which has path = '/'. That's pretty indicative of homepage'ish'ness.

A JavaScript knows only it's current context. It has no idea where in a site's hierarchy it is, so no, you can't check if you're on the homepage without already knowing the homepage's URL

Related

Manually generate GA linker parameter with gtag (GA4)

Background
To pass a client_id from one domain to another, Google supports adding a "linker" parameter to outgoing Links that are part of the cross-domain tracking setup. This linker parameter contains the client_id, session_id (I believe, information about Google Ads, e.g. gclid) and a basic fingerprint + timestamp. On the receiving domain, if the browser fingerprint matches and the timestamp is not too far in the past, the passed client_id and session_id are stored in a first party cookie on the 2nd domain and consequently used.
analytics.js / GA-UA
With analytics.js (GA-UA) you could easily do the following, to decorate URLs manually:
function decorateUrl(urlString) {
var ga = window[window['GoogleAnalyticsObject']];
var tracker;
if (ga && typeof ga.getAll === 'function') {
tracker = ga.getAll()[0]; // Uses the first tracker created on the page
urlString = (new window.gaplugins.Linker(tracker)).decorate(urlString);
}
return urlString;
}
Yet, when only gtag is loaded, window.ga and window.gaplugins are not defined. As far as I see, there is currently no documented way to manually generate links with the linker parameter with gtag.
In Google's documentation, they suggest setting up the linker manually. (https://support.google.com/analytics/answer/10071811?hl=en#zippy=%2Cmanual-setup)
But this has several disadvantages, e.g. I have to create a custom "fingerprint" logic (so that decorated URLs are not shared) and e.g. Google Ads information is not included.
Either way, I would like to use the internal gtag logic to decorate URLs.
"Hacky" Workaround Solution
gtag automatically decorates a tags (as soon as they're clicked) that lead to a cross-domain-tracking domain specified in the GA4 data stream settings (e.g. "test.com"), but I specifically need to decorate URLs manually (i.e. without immediately redirecting to them).
I thought about doing the following:
Create a dummy, hidden a tag with the URL to decorate
Prevent redirection with onclick='event.preventDefault();'
Simulate click on hidden element so that gtag automatically adds the linker url parameter to the href attribute
Extract new href attribute
Remove hidden element
function decorateUrlGtag(urlString) {
var tempAnchorEl = document.createElement("a");
tempAnchorEl.setAttribute("type", "hidden");
tempAnchorEl.setAttribute("href", urlString);
tempAnchorEl.setAttribute("onclick", "event.preventDefault(); return false");
document.body.appendChild(tempAnchorEl);
tempAnchorEl.click();
var urlWithLinker = tempAnchorEl.href;
tempAnchorEl.remove();
return urlWithLinker;
}
This also does not work, because gtag does not seem to register the tempAnchorEl.click(); call. If I click the link manually, the URL is decorated - as expected.
Suggested Solutions
The solutions outlined here (Google Analytics gtag.js Manually adding the linker cross-domain parameter to URLs) also do not work for me:
Answer: Even after gtag is initiated, I do not see a global ga element
Answer: Same problem (no ga defined)
Do you (1) know if there is a way to generate the linker parameter manually with gtag that I have overlooked, (2) know how to make my "hacky" solution work or (3) have another possible solution?
I haven't grokked this solution, and I am not sure it answers your question directly, but Simo does give an outline of how to configure GA4 cross domain tracking here:
https://www.simoahava.com/gtm-tips/cross-domain-tracking-google-analytics-4/#how-to-configure-cross-domain-tracking-manually
He breaks the problem down into steps but does not go into great detail. He provides one code snippet:
"...you could also load the URL parameter values directly into the GA4 configuration with something like:
gtag('config', 'G-12345', {
// Namespace roll-up trackers
cookie_prefix: 'roll-up',
// Pull in the Client ID from the URL
client_id: (new URLSearchParams(document.location.search)).get('client_id'),
// Pull in the Session ID from the URL
session_id: (new URLSearchParams(document.location.search)).get('session_id')
});
"
Hope that helps!

Google Extension HostEquals for chrome.history.deleteUrl or chrome.browsingData.remove

I am working on a chrome extension project, but cannot get host equals to work so it covers everywhere the user goes past the domain. For an example so if the user went to https://www.google.com/imghp?hl=en To have the code execute again there. Is this possible to do in the background.js file? I dont think match patterns will work here. The below code executes properly if set to an exact url chrome.history.deleteUrl({ url: 'www.google.com'} but not if I try to set it to hostEquals. I dont think this function allows hostEquals. Thank you for any help.
background.js file-
'use strict';
chrome.webNavigation.onCompleted.addListener(function() {
}, {url: [{urlMatches : 'www.google.com'}]});
var callback = function () {
alert("History is clearing");
};
chrome.history.deleteUrl(
{ url: [{hostEquals: 'www.google.com'}]}
, callback);
Is there a way I can past hostEquals in as a variable? HostEquals also does not work for chrome.browsingData.remove()
Please don't invent nonexistent properties: as the documentation says deleteUrl has only url property, which is "The URL to remove", not a pattern. If you want to remove all URLs from a domain then first find them using chrome.history.search. See also demo extensions.
A better solution might be to use details.url provided to onCompleted callback as you can see in the documentation. See also the demo extensions and look for more examples yourself.
chrome.webNavigation.onCompleted.addListener(details => {
chrome.history.deleteUrl({url: details.url});
}, {url: [{hostEquals: 'www.google.com'}]});
Another problem in your code was that urlMatches is the wrong tool because it's a regular expression that can match https://foo/bar/www1google2com in irrelevant URLs.
P.S. consider using onCommitted instead of onCompleted to perform the check earlier.

What are these Google-calendar events from?

It seems it's fairly common practice to grab the contents of a Google-calendar embed code, and add a stylesheet into it (either manually or through something like a PHP script) and display a custom-styled public calendar.
The odd thing is, I noticed if you click the print button at the top, or the "Google Calendar" in the lower right, it goes to localhost or whatever domain the page is - not the Google calendar.
If you try to trace the "gcal$func$[3]();" onclick through the Chrome devtools, or through Firefox with gcal$func$[3].toSource(); it will not find it or say
"function () {
[native code]
}"
So where is this function coming from, and how can you tweak this to make it open in a new window with the Google url, not the current domain (404)?
According to the Google Calendar embed JS code, the function points to the following code
window.open(Pf(this.c.i.Nb + "/render", "cid", b))
this.c.i.Nb represents the base URL, which is by default the domain where the script runs (in your case that's your domain). However, it's intended to be google.com domain and fortunately, it's very easy to change that. baseURL is one of the parameters in the initialization script (declared in the page you're grabbing) and you just need to configure that to https://www.google.com.
If you use PHP, your code might look like this.
$page = new DOMDocument("1.0", "utf-8");
// grab the Google Calendar code
$page->loadHTMLfile("https://www.google.com/calendar/embed?src=yourcalendar%40gmail.com");
// set up the baseUrl and print the grabbed page
echo str_replace('"baseUrl":"/"', '"baseUrl":"https://www.google.com/"', $page->saveHTML());
Now all the links should work correctly.

sammy.js url not found cause of subdirectory

Hi I create a spa with knockout, amplify and sammy.
If I now click an a link like:
#/page?s=About
it links to url.de/subdirectory/#/page?s=About which is right but the console fires following error:
GET url.de/About 404 (Not Found)
because it should be:
url.de/subdirectory/About
My sammy code is:
var app=$.sammy(function () {
// define prexecutes
// update parameters in appModel from request for all routes
this.before('', function() {
//setParameters(this);
});
// authenticate on any page except for login and logout routes
this.before({except: {path:/\/(login|logout|hp)/}}, function() {
});
// actual routes
// home
this.get('#/', function() {
appModel.page("home");
return false;
});
// content
this.get('#/page', function(eventContext) {
content(eventContext);
});
});
app.run('#/');
How do I get sammy not ignoring my subdirectory in which my site is?
You can try with another custom route definition like this
this.get('#/page/:s', function(eventContext) { // where s is parametre
content(eventContext);
});
also use url like this
#/page/About // it will read 'About' as value of parameter 's'
instead of
#/page?s=About
Hope this helps
I ran into a similar situation myself recently. I could not find any configuration options or workarounds that would allow Sammy.js to route to a subdirectory. My solution was to create a virtual host on the server hosting my app with the subdirectory as the subdomain in order to place the app at the document root. In your case, the virtual server would map from url.de/subdir/About to subdir.url.de/About. I realize that this may not be possible for you (since I don't know how much control you have over your hosting environment), but it got me moving again pretty quickly. Hope this helps.
P.S. As a small aside, I just browsed through the Sammy.js source at https://github.com/quirkey/sammy, and it appears that the subdirectory is stripped out (in error) to fix an IE quirk. https://github.com/quirkey/sammy/blob/master/lib/sammy.js#L301 may be the problem.

Google Chrome Extension - Background.html function question

Is there anyway by adding to this javascript I can ingore anything after the .com/ .net/ .org/ etc for tab.url.
So if tab.url = examplesite.com/blabla/blabla.html it will replace tab.url with examplesite.com/ and ignore anything after it.
Here's my background.html script.
<script type="text/javascript">
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.tabs.getSelected(null,function(tab) {
chrome.tabs.create( { url: "http://www.mysite.com/index.php?q=" +tab.url } );
});
});
</script>
Or do I need to program this into mysite to strip the Url? I was wondering if it is possible with Javascript... (not my forte.)
Thank you for any help you may be able to give me.
Unfortunately there is not parseUri function built into javascript but you could build what you're asking for using regular expressions. An example of this can be found here:
http://blog.stevenlevithan.com/archives/parseuri
Also, I've never tried to access it from a Chrome extension, but I suspect you have access to the window.location variable which is an object that contains broken down parts of the current page's url. Trying console.log(window.location) and look at the content of the object.

Categories

Resources