Сценарий Google Apps получает родительский URL для iFrame в Javascript
Я искал много форумов и уверен, что это будет нет, но я подумал, что открою это сообществу на всякий случай;)
Мне было поручено создать инструмент на наших страницах Сайтов Google, который бы регистрировал время посещения наших сотрудников после посещения страницы. Это помогает в подтверждении соответствия с доступом к документу, а также журналами активности. Если iFrame находится в том же домене, что и страница, на которой он размещен, довольно просто запросить URL родительской страницы изнутри фрейма, но ограничения безопасности ограничивают это для доменов или поддоменов.
Я надеюсь, что тот факт, что я встраиваю скрипт приложений Google в страницу сайтов Google, даст мне больше возможностей. До сих пор я пробовал команды document.referrer, parent.document.location, parent.window.document.location, parent.window.location, parent.document.location.href и те же команды с точки зрения окна и документа. Все они отвечают одинаково:
https://n-labp6vtqrpsdn12345neycmicqw7krolscvdkda-0lu-script.googleusercontent.com/userCodeAppPanel
Когда я хочу:
https://sites.google.com/mysite.com/mysite/test/test3
Есть ли у ветеранов Google дополнительные хитрости?
Редактировать: я только что попытался передать переменные через ссылку html в местозаполнитель изображения Google для сценариев приложений на сайтах Google и немного продвинулся дальше. Вы видите, я могу запустить этот URL: https://script.google.com/a/macros/coordinationcentric.com/s/AKfycbxDX2OLs4LV3EWmo7F9KuSFRljMcvYz6dF0Nm0A2Q/exec?test=hello&test2=howareyou и протестировать url ifl и протестировать переменные в отдельном окне. Если я пытаюсь встроить этот URL-адрес в HTML-страницу Сайтов Google, он выдает ошибку смешанного содержимого:
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.
Возможно, кто-то пробовал такой подход?
0 ответов
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!