Retrieve URL of AppScript using Javascript - javascript

I am trying to reload the current page with a new parameter, but I am unable to retrieve the correct URL of the webpage. I am getting an alternate URL instead of the one that triggers the web app
https://script.google.com/a/user/macros/s/A...ljhGC/dev?action=menu&id=1
when the button is clicked I want the action parameter's value to change and the page to reload as
https://script.google.com/a/user/macros/s/A...ljhGC/dev?action=checkout&id=1
Here is my javascript within the HTML File
console.log(document.url);
var url = new URL(window.location.href);
var query_string = url.search;
var search_params = new URLSearchParams(query_string);
search_params.set('action', 'checkout');
url.search = search_params.toString();
var new_url = url.toString();
window.location.replace(new_url);
console.log(new_url);
}
This is the URL that gets logged
https://n-ikwx...khq-1lu-script.googleusercontent.com/userCodeAppPanel?action=checkout
How do I retrieve the actual URL that is in the address bar?
Thanks in advance!

Issue:
A iframe with different origin cannot read the href property of location of the the parent/top frame, which is write only. So, You can't.
Solution:
You can however pass the url from server side.
Server side:
function getTopUrl(){
return ScriptApp.getService().getUrl();
}
Client side:
var topUrl;
function getTop(){
google.script.run.withSuccessHandler((url)=>{topUrl=url;}).getTopUrl();
}
window.addEventListener('load', getTop);
References:
Where is my iframe in the published web application/sidebar?
Same origin policy
Service#getUrl
google.script#run

Related

Fetch url of html page inside an iframe [duplicate]

Is there a simple way to get the current URL from an iframe?
The viewer would going through multiple sites.
I'm guessing I would be using something in javascript.
For security reasons, you can only get the url for as long as the contents of the iframe, and the referencing javascript, are served from the same domain. As long as that is true, something like this will work:
document.getElementById("iframe_id").contentWindow.location.href
If the two domains are mismatched, you'll run into cross site reference scripting security restrictions.
See also answers to a similar question.
If your iframe is from another domain, (cross domain), the other answers are not going to help you... you will simply need to use this:
var currentUrl = document.referrer;
and - here you've got the main url!
If you are in the iframe context,
you could do
const currentIframeHref = new URL(document.location.href);
const urlOrigin = currentIframeHref.origin;
const urlFilePath = decodeURIComponent(currentIframeHref.pathname);
If you are in the parent window/frame, then you can use https://stackoverflow.com/a/938195/2305243 's answer, which is
document.getElementById("iframe_id").contentWindow.location.href
I had an issue with blob url hrefs. So, with a reference to the iframe, I just produced an url from the iframe's src attribute:
const iframeReference = document.getElementById("iframe_id");
const iframeUrl = iframeReference ? new URL(iframeReference.src) : undefined;
if (iframeUrl) {
console.log("Voila: " + iframeUrl);
} else {
console.warn("iframe with id iframe_id not found");
}
Hope this will help some how in your case,
I suffered with the exact same problem, and just used localstorage to share the data between parent window and iframe.
So in parent window you can:
localStorage.setItem("url", myUrl);
And in code where iframe source is just get this data from localstorage:
localStorage.getItem('url');
Saved me a lot of time.
As far as i can see the only condition is access to the parent page code.
Hope this will help someone.
If you're inside an iframe that don't have cross domain src, or src is empty:
Then:
function getOriginUrl() {
var href = document.location.href;
var referrer = document.referrer;
// Check if window.frameElement not null
if(window.frameElement) {
href = window.frameElement.ownerDocument.location.href;
// This one will be origin
if(window.frameElement.ownerDocument.referrer != "") {
referrer = window.frameElement.ownerDocument.referrer;
}
}
// Compare if href not equal to referrer
if(href != referrer) {
// Take referrer as origin
return referrer;
} else {
// Take href
return href
}
}
If you're inside an iframe with cross domain src:
Then:
function getOriginUrl() {
var href = document.location.href;
var referrer = document.referrer;
// Detect if you're inside an iframe
if(window.parent != window) {
// Take referrer as origin
return referrer;
} else {
// Take href
return href;
}
}
I've been trying to retrieve the full URL from the inside of the shopify google analytics additional script iframe. document.refferer shows only hostname without search params. But I found another property that worked for me document.baseURI
Some additional information for anyone who might be struggling with this:
You'll be getting null values if you're trying to get URL from iframe before it's loaded.
I solved this problem by creating the whole iframe in javascript and getting the values I needed with the onLoad function:
var iframe = document.createElement('iframe');
iframe.onload = function() {
//some custom settings
this.width=screen.width;this.height=screen.height; this.passing=0; this.frameBorder="0";
var href = iframe.contentWindow.location.href;
var origin = iframe.contentWindow.location.origin;
var url = iframe.contentWindow.location.url;
var path = iframe.contentWindow.location.pathname;
console.log("href: ", href)
console.log("origin: ", origin)
console.log("path: ", path)
console.log("url: ", url)
};
iframe.src = 'http://localhost/folder/index.html';
document.body.appendChild(iframe);
Because of the same-origin policy, I had problems when accessing "cross origin" frames - I solved that by running a webserver locally instead of running all the files directly from my disk. In order for all of this to work, you need to be accessing the iframe with the same protocol, hostname and port as the origin. Not sure which of these was/were missing when running all files from my disk.
Also, more on location objects: https://www.w3schools.com/JSREF/obj_location.asp

How to obtain one part of the url using javascript only

This is about a password reset link sent to the email from firebase. I want to get the oobCode from it. But when I obtain the url of the page , it gives me the local address not the actual link I clicked in my email.Please help
https://example.com/usermgmt?mode=resetPassword&oobCode=ABC123&apiKey=AIzaSy...&lang=fr
This link actually loads the reset_pwd.html in my website. So when I try to get window.location.href , it doesnt give me the actual address displayed in the address bar.
This is what I have tried so far. But I realised I' m trying to split the local address of the web page http://127.0.0.1:80/reset_username
function func() {
var s = window.location.href;
ResponseURL = window.location.href;
var domain = ResponseURL.split('=');
alert(s);;
}
You can get it using URL.searchParams.get():
function getUrlParam(key, urlString = window.location.href) {
let url2 = new URL(urlString);
return url2.searchParams.get(key);
}
const url = `https://example.com/usermgmt?mode=resetPassword&oobCode=ABC123&apiKey=AIzaSy&lang=fr`;
console.log(getUrlParam('oobCode', url));
// Can be used without providing the URL, like:
// getUrlParam('oobCode');

Trying to post url segment to firebase

I am running a script on a public webpage and i want to post part of the url into firebase.
I can insert a button that retrieves the url segment as a string variable but I can't post automatically to firebase from the open page because of permissions. Is there any way to do this other than creating an external page and posting the variable manually? Here is the Script I am using. This runs fine in external pages but i want to run it from the public page.
function pushit() {
firebase.initializeApp(config);
var url = location.href;
var filename = url.substr(38, 8);
console.log("Push Successfull!!!");
var database = firebase.database();
var ref = database.ref('url/data'); var data = {url: filename }
ref.push(data);
}
The error get is:
Uncaught ReferenceError: pushit is not defined
at HTMLButtonElement.onclick (index.html)
I created a popup window instead, which sends the data to the Firebase. I realized that running this sort of code in other websites was not possible.

JQuery / Ajax - update URL without refreshing the webpage - should be compatible with IE8 and IE9

When I first load my webpage, it loads to this URL:
/default/
Now, when I click the "nextPost" button on the screen (which has an attribute called data-nextPostNumber), this is the code which I have:
event.preventDefault();
var nextPost = $(this).attr('data-nextPostNumber');
$("body").load("/default/?postNumber=" + nextPost);
So this loads the URL (assuming that nextPost=2)
/default/?postNumber=2
However, this was loaded using ajax so the actual URL in the URL bar is still
/default/
What I want to do is get the GET variables in the URL which was loaded through ajax. I have this code (which gets the GET variables in the URL and puts them in a dictionary called params):
function getQueryParams(qs) {
qs = qs.split("+").join(" ");
var params = {},
tokens,
re = /[?&]?([^=]+)=([^&]*)/g;
while (tokens = re.exec(qs)) {
params[decodeURIComponent(tokens[1])]
= decodeURIComponent(tokens[2]);
}
return params;
}
But this code just gets the GET variables in the URL which is in the URL bar - not the URL which was loaded using Ajax. So, is there a way for me to take the URL which was loaded using Ajax and place that URL in the URL bar? If not, is there any way for me to solve my issue? Please note that I need it to be compatible with IE8 and IE9.
You can use the new History API method pushState:
<input type="button" value="Post #2"
onclick="history.pushState(null, 'MyWebsite Post #2', 'http://mywebsite.com/?postNumber=2');" />
When you click this button, the location will change to http://mywebsite.com/?postNumber=2 and then you can call your getQueryParams function as follows:
getQueryParams(location.search);
The pushState will NOT work if you open the page as a file, in another words, it must come from a webserver (it works with localhost)

Get Current location of Iframe [duplicate]

Is there a simple way to get the current URL from an iframe?
The viewer would going through multiple sites.
I'm guessing I would be using something in javascript.
For security reasons, you can only get the url for as long as the contents of the iframe, and the referencing javascript, are served from the same domain. As long as that is true, something like this will work:
document.getElementById("iframe_id").contentWindow.location.href
If the two domains are mismatched, you'll run into cross site reference scripting security restrictions.
See also answers to a similar question.
If your iframe is from another domain, (cross domain), the other answers are not going to help you... you will simply need to use this:
var currentUrl = document.referrer;
and - here you've got the main url!
If you are in the iframe context,
you could do
const currentIframeHref = new URL(document.location.href);
const urlOrigin = currentIframeHref.origin;
const urlFilePath = decodeURIComponent(currentIframeHref.pathname);
If you are in the parent window/frame, then you can use https://stackoverflow.com/a/938195/2305243 's answer, which is
document.getElementById("iframe_id").contentWindow.location.href
I had an issue with blob url hrefs. So, with a reference to the iframe, I just produced an url from the iframe's src attribute:
const iframeReference = document.getElementById("iframe_id");
const iframeUrl = iframeReference ? new URL(iframeReference.src) : undefined;
if (iframeUrl) {
console.log("Voila: " + iframeUrl);
} else {
console.warn("iframe with id iframe_id not found");
}
Hope this will help some how in your case,
I suffered with the exact same problem, and just used localstorage to share the data between parent window and iframe.
So in parent window you can:
localStorage.setItem("url", myUrl);
And in code where iframe source is just get this data from localstorage:
localStorage.getItem('url');
Saved me a lot of time.
As far as i can see the only condition is access to the parent page code.
Hope this will help someone.
If you're inside an iframe that don't have cross domain src, or src is empty:
Then:
function getOriginUrl() {
var href = document.location.href;
var referrer = document.referrer;
// Check if window.frameElement not null
if(window.frameElement) {
href = window.frameElement.ownerDocument.location.href;
// This one will be origin
if(window.frameElement.ownerDocument.referrer != "") {
referrer = window.frameElement.ownerDocument.referrer;
}
}
// Compare if href not equal to referrer
if(href != referrer) {
// Take referrer as origin
return referrer;
} else {
// Take href
return href
}
}
If you're inside an iframe with cross domain src:
Then:
function getOriginUrl() {
var href = document.location.href;
var referrer = document.referrer;
// Detect if you're inside an iframe
if(window.parent != window) {
// Take referrer as origin
return referrer;
} else {
// Take href
return href;
}
}
I've been trying to retrieve the full URL from the inside of the shopify google analytics additional script iframe. document.refferer shows only hostname without search params. But I found another property that worked for me document.baseURI
Some additional information for anyone who might be struggling with this:
You'll be getting null values if you're trying to get URL from iframe before it's loaded.
I solved this problem by creating the whole iframe in javascript and getting the values I needed with the onLoad function:
var iframe = document.createElement('iframe');
iframe.onload = function() {
//some custom settings
this.width=screen.width;this.height=screen.height; this.passing=0; this.frameBorder="0";
var href = iframe.contentWindow.location.href;
var origin = iframe.contentWindow.location.origin;
var url = iframe.contentWindow.location.url;
var path = iframe.contentWindow.location.pathname;
console.log("href: ", href)
console.log("origin: ", origin)
console.log("path: ", path)
console.log("url: ", url)
};
iframe.src = 'http://localhost/folder/index.html';
document.body.appendChild(iframe);
Because of the same-origin policy, I had problems when accessing "cross origin" frames - I solved that by running a webserver locally instead of running all the files directly from my disk. In order for all of this to work, you need to be accessing the iframe with the same protocol, hostname and port as the origin. Not sure which of these was/were missing when running all files from my disk.
Also, more on location objects: https://www.w3schools.com/JSREF/obj_location.asp

Categories

Resources