google-apps-scripthttp-redirectweb-applications

Update Browser URL on Redirect


We are encountering an issue with a Google Apps Script web app designed to redirect users to a specific Google document based on an ID provided in the URL. The redirection itself works, but the browser's URL does not update to reflect the final destination URL. Instead, it remains as the original web app URL.

Desired Behavior

When a user enters a URL with a Google document ID into our web app, the web app should locate the document and redirect the user to it. Ideally, the browser's URL should update to show the document's URL after the redirection.

Example:

User-entered web app URL:
https://script.google.com/a/macros/<my-domaon>/s/<my-appscript-id>/exec/<my-google-doc-id>

Final document URL after redirection:
https://docs.google.com/document/d/<my-google-doc-id>

Attempts to Solve the Issue

1. Standard JavaScript Redirection:

2. Using google.script.history API:

3. HTML Meta Refresh Tag:

4. JavaScript window.location.href:

<html>
<head> 
<script>
window.location.href = "document_url";
</script> 
</head>  
<body>  
<p>If you are not redirected automatically, <a href="document_url">click here</a>.</p>  
</body>  
</html>

Result: Redirection works, but the browser URL remains as the web app URL.

5. JavaScript window.location.replace with history.pushState:

<html>
<head>
<script>
history.pushState(null, '', 'document_url');
window.location.replace('document_url'); 
</script>
</head> 
<body> 
<p>If you are not redirected automatically, <a href="document_url">click here</a>.</p> 
</body> 
</html>

Result: Redirection works, but the browser URL does not update as expected.

Additional Considerations

Request for Assistance

We are seeking insights or solutions to ensure that the browser's URL updates to the final destination URL after the redirection.


Solution

  • It appears that Google sandboxes app scripts - here's an excerpt from some documentation:

    To protect users from being served malicious HTML or JavaScript, Apps Script uses iframes to sandbox HTML-service web apps or custom user interfaces for Google Docs, Sheets, and Forms. (The HTML service does not use a sandbox in other situations, like generating the body of an email.) The sandbox imposes limitations on client-side code.

    This would make all of your attempts to change the URL futile as all of the methods you've chosen would update the iframe location but not the main page location. Indeed, the documentation continues

    The allow-top-navigation keyword, which allows the content to navigate its top-level browsing context, is restricted and not set as an attribute in the sandbox. If you need to redirect your script, add a link or a button for the user to take action on instead.

    So, unfortunately it doesn't look like this is possible without requiring manual user intervention. You'd need to add a link with the attribute target="_top" to tell the browser to safely escape the frame