Tascal
Tascal

Reputation: 31

How do I get the current URL of the page in JS through an embed?

I'm using Google Sites and using their embed feature. This embed has HTML and JS. What I need is to get the current URL of the page (the sites.google.com link) and set that as a variable. I've tried window.location.href and 'https://' + window.location.hostname but both return the URL of the embed, which is a "googleusercontent.com" link. Is there any way to bypass the embed and get the URL of the parent page?

Upvotes: 2

Views: 941

Answers (2)

Corinne Jacobo
Corinne Jacobo

Reputation: 59

So I'm having this same issue. Spent hours on it yesterday, looking at numerous posts with no luck. Basic/general answer I've found: it's not possible to do this in the New Google Sites.

See this post for a LOT of varying answers relating to this type of issue.

I successfully got my own JS working (as intended) outside of Google Sites, in a sandbox. However, the iFrame that Google wraps all embeds in on the New Google Sites makes it so that when you retrieve the URL, it's not going to give you your own site's URL. And, if you try to do pretty much any work-around (I've tried all kinds of querySelector options, document.referrer, etc.), it'll either show an unintended URL (like "gstatic" as in the previous answer), or you'll be blocked for security reasons, because the origins are different. And, since the only way to add code to a Google Site is through an iFrame embed, there's no way around this issue.

Here are two simplistic options I tried for reference:

document.referrer method as mentioned previously

var currentLink = document.referrer;

console.log(currentLink);

querySelector method to try to extract URL from a meta tag

const meta = document.querySelector("meta[itemprop='url']");
const content = meta.getAttribute("content");

console.log(content); // https://sites.google.com/yoursite/home
<meta itemprop="url" content="https://sites.google.com/yoursite/home">

So, for anyone not on Google sites, feel free to use these code snippets, since they'll work as intended. But I've confirmed that they fail when embedded in a Google Site, and I've found no reliable workaround.

Upvotes: 1

RedDeath
RedDeath

Reputation: 322

You can try calling document.referrer however for Google Sites it will return "https://www.gstatic.com/" since it seems that Google wraps the iFrame in some component of theirs.

Upvotes: 1

Related Questions