Google Apps script get Parent URL to iFrame in Javascript - javascript

I've searched many forums and am pretty confident this will be a no, but I thought I would open it up to the community just in case ;)
I've been tasked with creating a tool on our Google Sites pages that records the visit times of our employees after visiting a page. It helps with confirming compliance with document access as well as activity logs. If an iFrame is on the same domain as the page it is hosted on, it's fairly easy to query the URL of the parent page from within the frame, but security limitations restrict this across domains or sub-domains.
I'm hoping that the fact that I am embedding a Google apps script into a Google sites page will give me more options. So far, I have tried the commands document.referrer, parent.document.location, parent.window.document.location, parent.window.location, parent.document.location.href, and the same commands from window and document perspectives. They all respond the same:
https://n-labp6vtqrpsdn12345neycmicqw7krolscvdkda-0lu-script.googleusercontent.com/userCodeAppPanel
When I want:
https://sites.google.com/mysite.com/mysite/test/test3
Do any Google veterans have additional tricks?
Edit: I've just tried to pass variables via an html link the Google image placeholder for Apps Scripts on Google Sites and got a tad bit farther. You see, I can run this url: https://script.google.com/a/macros/coordinationcentric.com/s/AKfycbxDX2OLs4LV3EWmo7F9KuSFRljMcvYz6dF0Nm0A2Q/exec?test=hello&test2=howareyou and get the variables test1 and test2 if I run the url in a separate window. If I try to embed that URL into the HTML page on Google Sites, it throws this mixed-content error:
trog_edit__en.js:1544 Mixed Content: The page at
'https://sites.google.com/a/mysite.com/mysite/test/test3' was loaded over HTTPS, but requested an insecure image 'http://www.google.com/chart?chc=sites&cht=d&chdp=sites&chl=%5B%5BGoogle+Apps+Script%27%3D20%27f%5Cv%27a%5C%3D0%2710%27%3D499%270%27dim%27%5Cbox1%27b%5CF6F6F6%27fC%5CF6F6F6%27eC%5C0%27sk%27%5C%5B%22Apps+Script+Gadget%22%27%5D%27a%5CV%5C%3D12%27f%5C%5DV%5Cta%5C%3D10%27%3D0%27%3D500%27%3D197%27dim%27%5C%3D10%27%3D10%27%3D500%27%3D197%27vdim%27%5Cbox1%27b%5Cva%5CF6F6F6%27fC%5CC8C8C8%27eC%5C%27a%5C%5Do%5CLauto%27f%5C&sig=TbGPi2pnqyuhJ_BfSq_CO5U6FOI'. This content should also be served over HTTPS.
Has someone tried that approach, perhaps?

In short - I understand it's not possible to investigate a parent URL from an iFrame in Google Sites.
The content of iframes/embedded content is hosted all over the place, separate from the site itself. The Same-Origin rules prevent checking as you've found.
Your first URL "https://n-labp...googleusercontent.com..." is where the script itself is hosted. Any output from the script, like HTML, will appear to come from here.
You can embed HTML and javascript directly in Sites using the Embed function. If you investigate that, you'll find that it's hosted at something like "https://1457130292-atari-embeds.googleusercontent.com..."
Calling parent will always give this *-atari-based URL, rather then the actual page it's hosted on.
A fairly lightweight solution is to use a combination of the two.
Use simple doGet pings and handle the work in your Apps Script.
On your Site, use Embed feature to insert:
<!DOCTYPE html>
<html>
<body onbeforeunload="return depart()">
<script>
var page = "testpage"; // manually set a name for each page you paste this code in to
var script = "https://script.google.com/macros/s/... your script, ending with exec ...";
fetch(script+"?page="+page+"&direction=arrive");
function depart(){
fetch(script+"?page="+page+"&direction=depart");
}
</script>
</body>
</html>
Then in your Apps Script:
function doGet(e){
var httpParams = e.parameter ? e.parameter : "";
// params is an object like {"page": "testpage1", "n": "1"}
var getPage = httpParams.page ? httpParams.page : "";
var getDirection = httpParams.direction ? httpParams.direction : "";
/* Handle it as you please, perhaps like: */
var user = Session.getActiveUser().getEmail();
/* maybe use a temporary active key if open to non-Google users */
/* first-time Google users will have to authenticate, so embed one frame somewhere full-size maybe, or just tell users to go to the script's link */
/* hand off to a helper script */
var time = new Date();
var timeUTC = time.toUTCString(); // I like UTC
doSomethingWithThis(user, direction, timeUTC);
/* etc... */
/* Return some blank HTML so it doesn't look too funny */
return HtmlService.createHtmlOutput("<html><body></body></html>");
}
Then publish as a web app. If you'll use temporary active keys instead of Google accounts, you'll have the script run as you and be available to anyone, even anonymous.
You've probably already solved this, but I hope it can be of use to someone else who stumbles across it!

Related

Alert box after redirect

so i know this may sound stupid, but I want to know if there is any way that i could redirect someone to a website, and then display an alert box on the web page, using either javascript or any other interface that can be weaved into HTML5. I asked some of my classmates, and they didn't know, so I just need a confirmation that this isn't possible.
I have ran a few trials i found, but on further review, they wouldn't work.
edit I have control over the site, but I wish for the box to only pop up if i redirect it.
I can give the code if it would help, but I'm doubtful it will help
sorry for wasting your time if i did. thanks.
Similar to Gerard's answer, but using query strings. A possibly more standard solution.
On the first page:
<script>
window.location = 'https://{your website here}/?showAlert=true';
</script>
Then on the 2nd page.
const urlParams = new URLSearchParams(window.location.search);
const showAlert = urlParams.get('showAlert');
if(showAlert === "true") {
alert("Hello");
}
Note this will not work in internet explorer
You could communicate to the new site that it's a redirect by appending the route:
On the site you want to redirect from:
<script>
// if you can't use a normal link, change the url with JS
window.location = 'https://{your website here}/#redirect';
</script>
On the site you want to show the alert:
<script>
if (window.location.pathname.includes('#redirect') alert('What you want to say');
</script>
If you only have control over the first site, you could alert before redirecting, there wouldn't be much difference to the user since the alert blocks execution of other code.
You can call an alert box in a HTML document with JavaScript like this:
window.onload = function () {
alert("Hello World!");
}
-> https://jsfiddle.net/u8x6s31v/
You can also redirect somebody, if the page he's visiting is yours. Is that what you mean?
Update:
I think you can't see the URL where someone comes from with JavaScript. The only way to trigger scripts for some people is to add a hash.
window.onload = function () {
hashUrl = window.location.hash;
if (hashUrl == "#alert") {
alert("Hello World!");
}
}
Then call for example: domain.tld/path/index.html#alert
-> https://jsfiddle.net/u8x6s31v/1/
This is a vague questions with a lot of possible answers but seeing as how you're new, I'm going to speculate on what you might be asking and try to answer it.
It's not clear what you mean by "redirect".
Is this a server-side redirect like when you move/change a URL and you redirect the old URL to a new URL? Is this a Javascript meta refresh that you put in a 404 template? Is this a redirect that occurs after a user takes an action?
Regardless, you're going to have to "annotate" that user and then take action upon that annotation. The most obvious method would be based on the "referrer" HTTP header but it is also possible to do it based on the presence of a cookie.
Additionally, adding URL parameters to a redirect is trivially easy and often used for stuff like this.
The immediate things that come to my mind would be via Google Analytics (preferably implemented via Google Tag Manager because it'll make it easier).
Look into "outbound link tracking", "cross-domain tracking" and "UTM campaign tracking" (all related to Google Analytics and/or Google Tag Manager) and you'll probably find something that suits your needs.
URL shorteners are commonly used to mask parameters in links and there are open source libraries that allow you to host your own URL shortener (which you could integrate into your redirects) or do some other type of link tracking like is often used for affiliates.

Is there a solution to correctly open user authenticated URL from Microsoft Office programs?

The scenario I'm going to describe is about Excel, but you can spot the same problem in all Office tools.
Scenario:
In my default browser (NOT Internet Explorer) I'm logged in my own specific website, let's call it www.mypersonalwebsite.com
I have an Excel folder with the A1 cell containing a URL pointing to http://www.mypersonalwebsite.com/url/visible/only/to/loggedin/users
When I click on the URL in A1 cell:
my default browser is trying to open this URL
the website is refusing to serve the page because the request is coming from a non logged in user
So that's the problem: why is the browser complaining about the user session when I'm already logged in? And how can I solve it?
I found many similar questions about this problem on stackoverflow and I think I composed a portable and "definitive" solution to this problem.
First of all: why is the browser complaining about the user session?
The answer is "Microsoft Office Protocol Discovery". In a few words: it's something that works only if you are using Microsoft Windows and your default browser is Internet Explorer.
Basically, if you are not using Microsoft Windows OR your default browser is not Internet Explorer, when you click on an URL, the request sent to the browser will always be with an empty cookie. This means that, despite the default browser could use a correct cookie to authenticate the user, the request coming from Excel will never use it. But if you try to reload the page (and the webserver is not redirecting to a different error page), the browser will use the domain cookie and you'll see the correct page.
Second question: how can I solve this problem?
I think I found a very good solution, composed by an HTML part and a webserver part.
HTML part
Starting from the fact that you need to reload the page to use the cookie, I created a simple static page containing a little javascript code and some html. This is just an example. The main part of this code is here.
<!DOCTYPE HTML>
<html lang="en-US">
<head>
<script type='text/javascript'>
function getParameterByName(name) {
var match = RegExp('[?&]' + name + '=([^&]*)').exec(window.location.search);
return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
}
</script>
<meta charset="UTF-8">
<script type="text/javascript">
window.location.href = getParameterByName('newUrl');
</script>
<title>Page Redirection</title>
</head>
<body>
<!-- Note: don't tell people to `click` the link, just tell them that it is a link. -->
If you are not redirected automatically, follow the <a href='<?php echo $newUrl; ?>'>link</a>
</body>
</html>
You can access to the querystring via javascript in many ways, you can find a very interesting thread here.
This static page, let's call it redirect.html, will only do one thing: it will redirect the browser to the page specified in the newUrl parameter. Now if I put in the A1 cell something like:
http://www.mypersonalwebsite.com/redirect.html?newUrl=http://www.mypersonalwebsite.com/url/visible/only/to/loggedin/users
and if I click on this URL:
Excel will go to this URL using the default browser
The browser will open the redirect.html page with an empty cookie
The browser will reload the page using the domain cookie
The user will see the correct page as an authenticated user
The pros of this trick are: it works on all platforms and on all browsers supporting javascript. The cons are that we need to modify all URLs in all our Excel folders.
 The webserver part
To hide this redirection to the end users, and save us to modify all our Office documents, we can use another trick. In this example I will use nginx:
if ($http_user_agent ~* "(Excel|PowerPoint|Microsoft Office)") {
rewrite ^/(.*)$ /redirect.html?url=$1 break;
}
The meaning of this little if block is: if the incoming request is from a user agent like Excel, Powerpoint and so on, nginx will do an internal redirection to the redirect.html page, that will again do the browser redirection explained above.
This nginx redirect will completely hide the redirect trick, so we can use the original URLs and the users will always see the correct page.
I'm sure all this can be improved, and I would like to learn how to do it.
I hope this will help someone in finding a complete solution to this Office problem.

Showing documents from Google Drive on webpage

Is it possible to show the documents from my drive on a webpage? I want the user to be able to click the document and download it, directly from my drive. How would I go about doing this? Thank you for your suggestions.
The fastest and easiest solution is to embed the folder using an iframe (no javascript needed). Obviously this is also the least flexible solution, although you can use CSS to change the layout of the iframe contents (see below).
Google Drive won't allow embedding of the url you would normally use. It has its X-Frame-Options header set to "SAMEORIGIN", preventing use in an iframe. So you have to use the following link, which will allow embedding:https://drive.google.com/embeddedfolderview?id=DOCUMENT_ID#VIEW_TYPE
DOCUMENT_ID is the id that is mentioned in the normal share link (which looks like https://drive.google.com/folderview?id=DOCUMENT_ID), so you can just copy that from there.
VIEW_TYPE should be either 'grid' or 'list', depending on your preference.
And if you need to change the style of the iframe content, take a look at this solution.
For HTML/JavaScript solution, look at the following links:
https://developers.google.com/drive/quickstart-js
https://www.youtube.com/watch?v=09geUJg11iA
https://developers.google.com/drive/web/auth/web-client
Here's the simplest way using JavaScript, most of the complexity is in
your WebApp authorization. The example below reads files IDs, names and description in a folder you specify.
- go to: https://cloud.google.com/console/project
and create a new project "xyz"
- Select "APIs & auth", disable the ones you don't need, enable "Drive API"
- Select "Credentials",
push "CREATE NEW CLIENT ID" button
x Web Application
Authorized Javascript origins: "https://googledrive.com/"
Authorized redirect URI: "https://googledrive.com/oauth2callback"
it will result in:
Client ID: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com
Email address: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx#developer.gserviceaccount.com
Client secret: xxxxxxxxxxxxxxxxxxxx
Redirect URIs: https://googledrive.com/oauth2callback
Javascript Origins: https://googledrive.com/
- in the code below, replace
CLIENT_ID with xxxxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com
FOLDER_ID with the ID you see in the folder address line,
https://drive.google.com/?tab=mo&authuser=0#folders/xxxxxxxxxxxxxxxxxxx
- run it, authorize
I don't know if you read JS, the code can be followed from bottom up, I made is as simple as possible.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
var FOLDER_ID = '.xxxxxxxxxxxxxxxxxx'; // the folder files reside in
var CLIENT_ID = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com';
var SCOPE = //'https://www.googleapis.com/auth/drive';
[
'https://www.googleapis.com/auth/drive',
'https://www.googleapis.com/auth/drive.file', // for description,
];
function rsvpCB(resp) {
var picAlbumLst = '<ul>\n';
for (i=0; i<resp.items.length; i++)
picAlbumLst += (
' <li>'+resp.items[i].id+', '+resp.items[i].title+', '+resp.items[i].description+'</li>\n');
picAlbumLst += "</ul>\n";
$('#container').append(picAlbumLst);
}
function rqstCB() { //test # https://developers.google.com/drive/v2/reference/files/list
var rv = gapi.client.drive.files.list({
'q': '"'+FOLDER_ID+'" in parents and trashed = false',
'fields' : 'items(id,title,description)' //'items(id,title,description,indexableText)'
}).execute(rsvpCB);
}
// authorization server reply
function onAuthResult(authResult) {
var authButton = document.getElementById('authorizeButton');
authButton.style.display = 'none';
if (authResult && !authResult.error) { // access token successfully retrieved
gapi.client.load('drive', 'v2', rqstCB);
} else { // no access token retrieved, force the authorization flow.
authButton.style.display = 'block';
authButton.onclick = function() {
checkAuth(false);
}
}
}
// check if the current user has authorized the application.
function checkAuth(bNow) {
gapi.auth.authorize({'client_id':CLIENT_ID, 'scope':SCOPE, 'immediate':bNow}, onAuthResult);
}
// called when the client library is loaded, look below
function onLoadCB() {
checkAuth(true);
}
</script>
<script src="https://apis.google.com/js/client.js?onload=onLoadCB"></script>
<body style="background-color: transparent;">
<input type="button" id="authorizeButton" style="display: none" value="Authorize" />
<div id="container">
</div>
</body>
This should be done with Google API. You can search google drive php api list files on google. And also I found this and this on SO.
Here are some main points:
Do you want anyone with the URL to be able to see your document? You can share a document as public to anyone on the internet. Plus you can set read access to specific folders. Just right click a Google Doc file, and choose 'Share' from the short cut menu.
I'm assuming you want people to download your docs, even when you are not signed in. This is called 'Offline Access', and is one of many terms you'll need to figure out in order to do all of this with a program.
If you only want to give read access to the user, using JavaScript, jQuery, etc on the front end is a viable option. You can also do this in PHP, it's just a matter of personal preference.
To do all of this in code, you need to grant authorization to read your files. The oAuth2 process has multiple steps, and it's good to understand the basic flow. Setting up the code and the webpages to initially grant authorization, then retrieve and store the tokens can get confusing.
Your Google Project has a setting for where the origin of the authorization request is coming from. That is your website. But if you want to develop and test locally, you can set the Javascript Origins to http://localhost
How much time do you have, and how much programming experience? Would it be easier to give the user a few lines of instruction to "Manually" download your file, rather than program the authorization check?
Putting the document into your webpage is the easy part.
In order to embed a Google doc in your website, go to your Google Drive, open a document and choose File then Publish to Web, and you will be given an HTML iFrame Tag that can be embedded into you web page. You can change the height and width of the iFrame to match the document size. iFrame Instructions W3Schools
Downloading your document can be done very easily from the online version of a shared document just by choosing FILE and then DOWNLOAD AS from the menu.
To get up and running fast, just give the user a couple lines of instructions on how to download "Manually", then see if you can program the code.
Provide a link to your shared document instead of programming the button, and then work on the code.
Search Git Hub for Google Drive, you might find something there.
Some of the official Google code examples are way more complicated than you need, and will take a long time to figure out. The code examples in the documentation pages are simpler, but are almost never complete functioning code examples. You'll need to put lots of pieces of the puzzle together to make it work.

Content Script cross domain or message passing

I am writing a javascript extention that modifies a website. The extention adds a button to the website, and when clicked it modifies the page content. My script has to send cross domain xmlhttprequests to websiteB, and gets permissions upon installation to do so.
My problem is that the code that runs in the content scope of the website that I am modifying does not have permission to do cross domain requests, because it is within a content scope of the webpage. Nor can I easily pass variables between my main extention code and the code that runs upon the button click on the page.
These are the relevant parts of my code:
// ==UserScript==
// #include http://www.WebsiteB.com/*
// #match http://www.WebsiteB.com/*
// ==/UserScript==
var a = 1;
button.innerHTML = 'clickMe';
menu.appendChild(button);
contentEval(function() {
myFunc = function() {
//a is undefined
//this part does not have cross domain request permission
};
}
I use contentEval taken from http://wiki.greasespot.net/Content_Script_Injection to get the relevant code to be able to interact with the page my script is running on. Without it, I would not be able to call myFunc from a button on the website.
variables can not be transferred from the main code area to myFunc() by passing them directly using myFunc(a) either. myFunc(1) works, but does not suit my needs.
It's possible that I am going about things the wrong way. If so, please enlighten me.
Is there a way to have cross domain permissions from the code that interacts with the web page?
If not, what should I use to do message passing from the main code area to the content script of the page?

Checking if a website doesn't permit iframe embed

I am writing a simple lightbox-like plugin for my app, and I need to embed an iframe that is linked to an arbitrary page. The problem is, many web sites (for example, facebook, nytimes, and even stackoverflow) will check to see if is being embedded within a frame and if so, will refresh the page with itself as the parent page. This is a known issue, and I don't think there's anything that can be done about this. However, I would like the ability to know before hand if a site supports embed or not. If it doesn't, I'd like to open the page in a new tab/window instead of using an iframe.
Is there a trick that allows me to check this in javascript?
Maybe there is a server-side script that can check links to see if they permit an iframe embed?
I am developing a browser extension, so there is an opportunity to do something very creative. My extension is loaded on every page, so I'm thinking there's a way to pass a parameter in the iframe url that can be picked up by the extension if it destroys the iframe. Then I can add the domain to a list of sites that don't support iframe embed. This may work since extensions aren't loaded within iframes. I will work on this, but in the meantime....
Clarification:
I am willing to accept that there's no way to "bust" the "frame buster," i.e. I know that I can't display a page in an iframe that doesn't want to be in one. But I'd like for my app to fail gracefully, which means opening the link in a new window if iframe embed is not supported. Ideally, I'd like to check iframe embed support at runtime (javascript), but I can see a potential server-side solution using a proxy like suggested in the comments above. Hopefully, I can build a database of sites that don't allow iframe embed.
Check x-frame-options header by using following code
$url = "http://stackoverflow.com";
$header = get_headers($url, 1);
echo $header["X-Frame-Options"];
If return value DENY, SAMEORIGIN or ALLOW-FROM then you can't use iframe with that url.
Probably pretty late but what you need to do is make a request, likely from your server and look for the x-frame-options header. If it's there at all you can just open a new tab because if it is there is is one of the following: DENY, SAMEORIGIN, ALLOW-FROM. In any of these cases it's likely that you don't have access to open it in an iframe.
This subject has been discussed forever on the web with a particularly interesting (failed) attempt here:
Frame Buster Buster ... buster code needed
The bottom line is that even if you are able to construct a proxy that parses the contents of the page that you want in your iframe and removes the offending code before it is served to the iframe you may still come under "cease and desist" from the site if they get to hear about you doing it.
If you don't want your development to be widely available, you could probably get away with it. If you want your development to become popular, forget about it, and build a less underhand way of dealing with it.
Or develop it for mobile only... ;)
UPDATE: OK following on from your comment here's a bit of taster:
in javascript capture the click on the link
$("a").click(function(e){
preventDefault(e); // make sure the click doesn't happen
// call a server side script using ajax and pass the URL this.href
// return either a true or false; true = iframe breakout
// set the target attribute of the link to "_blank" for new window (if true)
// set the target attribute of the link to "yourframename" for iframe (if false)
// only now load the page in the new window or iframe
});
server side in PHP
$d = file_get_contents($url); // $url is the url your sent from the browser
// now parse $d to find .top .parent etc... in the <head></head> block
// return true or false

Categories

Resources