I made a small web app that opens when the user clicks a link in a spreadsheet. The link will take them to web app, which makes changes to a spreadsheet.
I want the browser window to close automatically once the code is finished running.
function doGet(e){
// code make changes to spreadsheet
// here I want browser window to close
return HtmlService.createHtmlOutput(uniqueid + " is marked complete");
};
Thanks for help
A distinction needs to be made between a Web App in a browser tab, and a sidebar or dialog box inside of a Google document (Sheet, Form, Doc).
The question is about a Web App in a browser tab. If you want to close a sidebar or dialog box, then just use:
google.script.host.close()
But this question is for a Web App. You can try putting a script tag in the HTML with code that runs automatically when the window is opened.
<script>
window.top.close();
</script>
If you want a delay:
<script>
setTimeout(function(){ window.top.close(); }, 3000);
</script>
You can try using window.onload.
<script>
window.onload=function(){
console.log("This onload did run");
setTimeout(function(){ window.top.close(); }, 3000);
};
</script>
If you don't care whether the user sees anything or not, you could just run Apps Script Content Service.
I came across your question long after you asked it, but in case you or anyone else is looking for the answer, try this:
To get the browser window to close, create a simple HTML file that instructs itself to close with the instruction window.top.close() like this:
Close Window.html
<!DOCTYPE html>
<html>
<script>
window.top.close();
</script>
</html>
You need to return this as an HTML output so that when the Web App runs, it runs on the client side (as Sandy said in the previous answer). In your scenario, you are already returning an HTML output to inform that some "[uniqueid] is marked complete", and it is assumed that you DON'T wish to close this window after the script runs, else the user will not receive the prompt you intended. That is why you need to keep the instruction window.top.close() outside of the same HTML output that gives this alert. To achieve that, just comma-separate both HTML outputs as two return values.
Here are the two other files that I came up with to model a solution for your use case. FYI: I packaged the user-facing HTML in an email to provide a convenient point of execution, and the code will request an email address for delivery.
Code.gs
function doGet(e){
// code make changes to spreadsheet
var ss = SpreadsheetApp.openById([The key for the spreadsheet you wish you modify])
var sheet = ss.getActiveSheet()
var lastRow = sheet.getLastRow()
var params = JSON.stringify(e);
var paramsArray = JSON.parse(params)
sheet.getRange(lastRow + 1, 1).setValue('Code made changes to spreadsheet at ' + Date())
sheet.getRange(lastRow + 1, 2).setValue(paramsArray.parameter.change)
// here I want browser window to close
var uniqueid = "Someuniqueid"
return HtmlService.createHtmlOutputFromFile('Close Window'), HtmlService.createHtmlOutput(uniqueid + " is marked complete")
};
function mailIt() {
var emailAddress = Browser.inputBox('What email address do you want to send the WebApp to?')
var html = HtmlService.createTemplateFromFile('HTML Email to run Web App')
var htmlCode = html.getRawContent()
Logger.log(htmlCode)
MailApp.sendEmail({
name: "Publish WebApp for survey embed Test",
to: emailAddress,
subject: "Publish WebApp for survey embed Test",
htmlBody: htmlCode
})
}
HTML Email to run Web App
<!DOCTYPE html>
<html>
<form action=[Your current Web App URL in quotes]>
Send text to spreadsheet: <input type="text" name="change"><br>
<input type="submit" value="Submit">
</form>
</html>
Obviously, there are some unanswered questions--like why is it a requirement to automatically close a window while your Web App appears to open only a window that carries a message for the user--but I trust your use case is more complicated than that, and you and others can intelligently leverage the principals in this example to your advantage.
Use the following at the end of the script portion of the HTML file to close a currently open HTML window in Google Sheets:
google.script.host.close();
Instead of using two HtmlServices separated with coma in return statement of your doGet(e) function (that has not worked for me - I got only one return value)
you can put window.top.close(); in onClick event of your submit button like this:
Replace:
<input type="submit" value="Submit">
With:
<input type="submit"
onclick="this.value='Magic ...';
google.script.run.withSuccessHandler(closeWindow); ">
and add somewhere in your html:
<script>
function closeWindow() { window.top.close(); }
</script>
I hope this will be of some use to someone somewhere someday :)
Cheers :)
Related
I want to save some JavaScript code as a bookmark in chrome so it automatically opens my university login site and clicks on on the login button. I am completely inexperienced in JavaScript, so I have no clue how to do this. I snipped together the following code, which opens the correct website, but then does not click on anything. The first URL automatically puts me to the login site (third URL in the code) in case I have not logged in yet in this window.
(function() {
window.location.replace("https://lms.uzh.ch/auth/MyCoursesSite/0");
window.onload = function(){
if (current_url.startswith('https://lms.uzh.ch/auth/MyCoursesSite/0')) {
return;
}
if (current_url.startsWith('https://lms.uzh.ch/dmz/')) {
document.getElementById("wayf_submit_button").click();
}
};
})();
I'm sorry if this is too obvious a question and annoys any experts but as I said I am a complete beginner. I would of course add the "javascript:" at the beginning for chrome to understand the bookmark.
When you use window.location.replace, you change the address and you code can't work anymore.
I can suggest using some browser extension, your "click function" should work then.
I guess you could also try to make some simple html page with iframe, you call your "click function" at this page, but you target it to the iframe. After that you can change browser's location to the university's webpage as you should already be logged in.
<html>
<head>
</head>
<body>
<iframe src="your_university_address.com" id="some_id" onload="click_button()"></iframe>
<script>
function click_button()
{
my_iframe=document.getElementById('some_id');
my_iframe.contentDocument.getElementById('your_button_id').click();
}
</script>
</body>
</html>
Very simple but it should do that job.
(You can achieve similar result by using window.open() I guess)
So I have a google site that I use for html hosting and I want to make a button that replaces the current window with a search window. So I do the normal routine:
<button onclick="doThis();">🔎</button>
<script>
function doThis(){
window.location="https://sites.google.com/example/search";
}
</script>
It replaces the window but just says "sites.google.com refused to connect".
Anyone know what's going on?
Try to use
window.location.assign()
<script>
function doThis(){
window.location.assign("https://sites.google.com/example/search");
}
</script>
And "https://sites.google.com/example/search" does not exist.
If you want to go to the search page, use: "https://www.google.com/"
If you want to use a goodle search engine for your website, you have to do something like this:
Passing html form values to google search query
I want the user to be able to open the website and there will be a prompt that will ask the user to tell them about themselves and the text they input display in a new window?
<html>
<head>
<script>
var text = prompt("Tell us something about yourself ");
function newWindow() {
var OpenWindow = window.open("", "slayyyter", "height=300 , width=300");
}
function showText() {
OpenWindow.document.write(text);
}
</script>
</head>
<body>
<button onclick="showText()">A</button>
</body>
</html>
The code has three errors in it. Open the web console (typically by pressing F12) to see messages for some of them.
The prompt string
"Tell us something about
yourself"
has a line feed in it that needs to be removed,
The variable OpenWindow declared in newWindow is not in scope of the code inside showText. If declaring OpenWindow globally, remove var before the variable name inside newWindow to prevent the global variable being shadowed by a local declaration.
newWindow needs to be called
Here's an example that returns the window object instead of saving it in a global variable:
<!DOCTYPE html>
<html>
<meta charset="utf-8">
<title>Test</title>
<head>
<script>
"use strict";
var text = prompt("Tell us something about yourself");
function newWindow() {
return window.open("", "slayyyter",
"height=300 , width=300");
}
function showText() {
var openWindow = newWindow();
newWindow().document.write(text);
newWindow.close();
}
</script>
</head>
<body>
<button onclick="showText()"> A </button>
</body>
</html>
Note
document.write is useful for learning exercises in JavaScript, but call document.close to finalize a document after writing to it - it stops the window loading indicator in opened windows.
Seach on "HTML5 document type declaration", "Declaring the character set in HTML" and "when to use strict mode in JavaScript" for more information.
You'll want to use your browser's tools and JavaScript console, which on button click says that OpenWindow is not defined. This is because of scope. OpenWindow only exists where you define it - inside function newWindow. To access it in other functions declare it outside (right under var text will do). You can leave it defined but blank, then assign it later. So under the declaration of "text" just put var OpenWindow;. Then inside newWindow delete "var" from in front of OpenWindow. You may have other issues as I have not tested the code, but that's the main one.
Hints:
read up on scope
read up on browser debug tools, especially JS console
do your tutorials in http://jsfiddle.net or something similar, and you can share examples here when you ask for help.
I'm afraid what you want to achieve isn't doable that easily because there is no direct way to tell the new browser window what you have written in the first window.
You can do it like this however.
Prompt to enter some text
Save the entered text into the browser's localstorage.
Open the same html page using window.open() but append a query string to the url e.g. ?id=new
Make a distinction via code if the site was called with or without a query string. If there's no query string show the prompt dialog, if there is a query string get the text from the localStorage and write it to the browser window.
Use this snippet and save it as test.html
<html>
<head>
<script type="text/javascript">
var urlParams = new URLSearchParams(window.location.search);
if (urlParams.get('id') == null) {
var text = prompt("Tell us something about yourself");
localStorage.setItem('myText', text);
window.open("test.html?id=new", "slayyyter");
} else {
document.write("You have written: " + localStorage.getItem('myText'));
}
</script>
</head>
</html>
As a side note - window.open() accepts an url as the first parameter. You can't simply enter some text or pass a string containing text - it must be a valid resource e.h. an image, a html file, php,...
I've got what appears to be a common scenario. I have a page where someone fills out a form and rather than redirecting to a different thank you page all the tracking needs to take place on the same page.
I found this link here that explains a solution which I implemented as per the below after a successful submission (conversion ID is 11111111 and the label is 22222222).
$("#conversion-script").prop('src', '//www.googleadservices.com/pagead/conversion.js');
$("#ga-code img").prop('src', '//www.googleadservices.com/pagead/conversion/11111111/?value=0&label=22222222&guid=ON&script=0');
When this gets executed I'm monitoring the network tab for developer tools and see that the GoogleAdServices.com address gets called successfully, and not only that but I have Google Tag Assistance (Chrome extension) running and when this event fires it comes up under "Tags Found" and says "working".
When I check the adwords account however, it's not showing up. I've confirmed that the tracking codes are all correct, and the first one was made 7 days ago.
Ideas?
For example you have such button:
<a href = '#' class = 'add_to_cart'><img src = 'btn_buy.png'></a>
Try this script:
<SCRIPT src='/js/jquery.js' type=text/javascript></SCRIPT>
<SCRIPT type=text/javascript>
$(document).ready(function()
{
var add_to_cart_processed = false;
$('.add_to_cart').click(function()
{
if (!add_to_cart_processed)
{
$('body').append('<div id = "remarketing_basket" style = "display:none"></div>');
$('#remarketing_basket').load('/add_basket.txt');
}
});
});
</SCRIPT>
In file add_basket.txt you need to save your conversion code.
I have been to some css/html/js discussing board which provide a text box to enter the html and a "Run it!" button to run the html in new pops up window.
I want to make one also, which is easy in jQuery:
function try_show_result() {
var code = $("#try-input").val();
if (code !== "") {
var newwin = window.open('','','');
newwin.opener = null; // 防æ¢ä»£ç 修改主页
newwin.document.write(code);
newwin.document.close();
}
}
But then I found a security problem: the pops up window has all the abilities of running an arbitrary javascript. So that when another authenticated user runs a given piece of code on the page, then it could stealing cookies or access some url that is only for the specified user only through ajax posts.
Is there an easy way to avoid this?
Update: I added newwin.document.cookie="" before open the window, not sure if this is better.
Is there an easy way to avoid this?
No
That is why Facebook went out and wrote their own version of JavaScript [FBJS].