get current page url

2019-05-04 05:26发布

问题:

On a web app using GAS HtmlService I need to get the url of current page to build a new link within a template.

The web app will run in a Google sites page (GAS as gadget) but also standalone

I am trying "var pageUrl = document.location.href" and then use pageUrl within a Html template like follow. I know it's wrong, but I am lost, Sorry.

<a href="<?= pageUrl + "?item=xyz" ?>" >Item xyz link</a>

Thanks, Fausto

回答1:

You can get the url for a webapp via ScriptApp:

<a href="<?= ScriptApp.getService().getUrl() + "?item=xyz" ?>" >Item xyz link</a>

and you can get the url in sites via SitesApp:

SitesApp.getActivePage().getUrl()

although I don't think that's actually useful for what you seem to be describing since you can't add useful query parameters to it. Scripts run in iframes, so although you can use document.location on the client, it won't help you anyways. The URL is sanitized and the service id is stripped out.



回答2:

Can you afford to go the jQuery route?

$(document).ready( function() {

var currentURL = window.location;

$('#myLink').prop('href', currentURL);


});

Then...

<a id="myLink" href="">Link to somewhere</a>


回答3:

Nowadays (since the Sites change in 2016) the answer is a bit simpler:

var current_url = DocumentApp.getActiveDocument().getUrl();