Google Apps Script OAuth2 in onOpen() not working - javascript

I'm using a script within my Sheets document to grab data from Google Search Console. The script uses an OAuth2 library from GitHub, which seems to work perfectly most of the time.
I'm using a function to check whether the user still has API access - called hasAccess() - in order to display menu items appropriately. The trouble is, though the function works everywhere else, it doesn't work in the onOpen function... the place I really need it to!
I was wondering whether this had anything to do with permissions? Any help would be greatly appreciated, as I'm losing the will to live!
You can see my code here (I've cut out most of the bits that seemed irrelevant):
// Setup on sheet open
function onOpen(e) {
// Set date validation
range = sheet.getRange('A2:A');
range.setDataValidation(dateRule);
// Check auth mode
if (e && e.authMode === ScriptApp.AuthMode.NONE) {
// Add an enable menu item (works in all authorization modes).
menu.addItem('Enable add-on', 'onOpen');
} else {
// Add setup option
menu
.addItem('Setup', 'setupDialog')
.addToUi();
// Check if API service has been authorized and allow functions
var service = getService();
// THE FOLLOWING RESULT IS ALWAYS FALSE :(
Logger.log(service.hasAccess());
if (service.hasAccess()) {
// Add start option
menu
.addItem('Start', 'startDialog')
.addToUi();
// Add get dates option
menu
.addItem('Get dates', 'getDates')
.addToUi();
}
}
// Add help option
menu
.addItem('Help...', 'helpDialog')
.addToUi();
}
function test() {
var service = getService();
// BUT THIS WORKS..?
Logger.log(service.hasAccess());
}
/*** OAUTH2 FUNCTIONS ***/
// Much of the following is adapted from Martin Hawksey's OAuth2 solution for Blogger - check it out!
// https://mashe.hawksey.info/2015/10/setting-up-oauth2-access-with-google-apps-script-blogger-api-example/
// Create OAuth2 service using library
function getService() {
// Create a new service with the given name. The name will be used when
// persisting the authorized token, so ensure it is unique within the
// scope of the property store.
return OAuth2.createService('searchConsole')
// Set the endpoint URLs, which are the same for all Google services.
.setAuthorizationBaseUrl('https://accounts.google.com/o/oauth2/auth')
.setTokenUrl('https://accounts.google.com/o/oauth2/token')
// Set the client ID and secret, from the Google Developers Console.
.setClientId(userProperties.getProperty('clientId'))
.setClientSecret(userProperties.getProperty('clientSecret'))
// Set the name of the callback function in the script referenced
// above that should be invoked to complete the OAuth flow.
.setCallbackFunction('authCallback')
// Set the property store where authorized tokens should be persisted.
.setPropertyStore(PropertiesService.getUserProperties())
// Set the scopes to request (space-separated for Google services).
// this is blogger read only scope for write access is:
// https://www.googleapis.com/auth/blogger
.setScope('https://www.googleapis.com/auth/webmasters.readonly')
// Below are Google-specific OAuth2 parameters.
// Sets the login hint, which will prevent the account chooser screen
// from being shown to users logged in with multiple accounts.
.setParam('login_hint', Session.getActiveUser().getEmail())
// Requests offline access.
.setParam('access_type', 'offline')
// Forces the approval prompt every time. This is useful for testing,
// but not desirable in a production application.
.setParam('approval_prompt', 'force');
}
// Handle OAuth2 callback
function authCallback(request) {
var searchConsoleService = getService(),
isAuthorized = searchConsoleService.handleCallback(request);
if (isAuthorized) {
return HtmlService.createHtmlOutput('Success! You can close this tab.');
} else {
return HtmlService.createHtmlOutput('Denied. You can close this tab');
}
}

The way I made for make onOpen function to works is as follows:
Create the onOpen function with your custom code (i.e. the functionality).
In your main function - the one that executes once the spreadsheet is open - , add the followind code:
// Set trigger programatically - adding the "onOpen" function:
ScriptApp.newTrigger("onOpen")
.forSpreadsheet(SPREADSHEET_ID)
.onOpen()
.create();
This is the full code:
/** This is the main function that executes once the spreadsheet is open: */
function startProgram() {
// Set trigger programatically - adding the "onOpen" function:
ScriptApp.newTrigger("onOpen")
.forSpreadsheet(SPREADSHEET_ID)
.onOpen()
.create();
}
/** onOpen function that adds items to select in the spreadsheet: */
function onOpen() {
var ui = SpreadsheetApp.getUi();
ui.createMenu('My Menu')
.addItem('Show message', 'showMessage_') // This is the name of the function to call.
.addToUi();
}
/** Show alert message. */
function loadCards_() {
SpreadsheetApp.getUi().alert("Today is: " + new Date());
}
Then, execute the code and reload/refresh the spreadsheet. You'll see the new menu with the item added to the spreadsheet.

Related

onOpen is not running to other users except to the owner. How to fix this? Google Script GAS

After refreshing the shared spreadsheet, onOpen is not running to other users who also have access.
But the owner is being able to run the codes and script.
Code.gs
function onOpen(e) {
test();
SpreadsheetApp.getUi() // Or DocumentApp, SlidesApp, or FormApp.
.createMenu('Custom Menu')
.addItem('First item', 'menuItem1')
.addToUi();
SpreadsheetApp.getUi() // Or DocumentApp, SlidesApp, or FormApp.
.createMenu('Custom Menu').addItem('Test', 'test').addToUi();
};
function test() {
var ui = SpreadsheetApp.getUi(); // Same variations.
var result = ui.prompt('Spreadsheet Restriction', 'Enter password:', ui.ButtonSet.OK);
// Process the user's response.
var button = result.getSelectedButton();
var text = result.getResponseText();
if (button == ui.Button.OK) {
// User clicked "OK".
} else if (button == ui.Button.CLOSE) {
// User clicked X in the title bar.
ui.alert('Spreadsheet is protected.');
test();
}
};
function myFunction() {
}
Already shared the access spreadsheet and script to other users but they can't still see it is working.
Appreciate your help guys... Thanks!
The users of your Sheet/script must have edit access on the Sheets document in order for the onOpen() trigger to be executed. From the documentation:
They do not run if a file is opened in read-only (view or comment) mode.
In order to use the prompt() method within the onOpen() function, you must use an installable trigger. Furthermore, the trigger must be set up by the user who is going to use it. The same also applies to other functions of the UI class such as showModalDialog().
This strict rules are most likely enforced in order to protect the end user of potential scams. If you are interested in protecting your Sheets document with password, I suggest you check out other solutions such as this one,
Reference
Simple Triggers restrictions
Installable Triggers restrictions

Google Apps Script send email through spreadsheet not working

I have a problem with some Google Script stuff. Basically, my goal is to have the script check to see if a client's case was resolved and then send an email to them that the issue has been resolved. I've gotten the logic done on when to send an email, but every time I try and implement it into the spreadsheet, I get the error:
Error
You do not have permission to call MailApp.sendEmail. Required permissions: https://www.googleapis.com/auth/script.send_mail (line 8).
I've got a simple function to test the functionality of it, and when run in the script editor it works fine, but not on the spreadsheet. Here is my sample function:
function myFunction(row) {
var sheet = SpreadsheetApp.getActiveSheet();
var rng = sheet.getRange(row, 1, 1, 2);
var ara = rng.getValues();
var email = ara[0][0];
MailApp.sendEmail(email, "TEST", "This is a test of sendEmail().");
return "Email sent.";}
According to the Apps Script Custom Functions documentation:
If your custom function throws the error message You do not have permission to call X service., the service requires user authorization and thus cannot be used in a custom function.
To use a service other than those listed above, create a custom menu that runs an Apps Script function instead of writing a custom function. A function that is triggered from a menu will ask the user for authorization if necessary and can consequently use all Apps Script services.
Method 1
Basically, you can replicate the wanted behavior of the two functions above with this:
function SendEmail() {
var message = "This is your response";
var subject = "You have feed back in the parking lot";
var ss = SpreadsheetApp.getActiveSheet();
var textrange = ss.getRange("F2");
var emailAddress = ss.getRange("B2").getValue();
if (textrange.isBlank() == false)
MailApp.sendEmail(emailAddress, subject, message);
}
And in order to trigger the execution of this function, you can make use of Apps Script triggers and choose one which is the most convenient for your use-case.
Method 2
You can also create a custom menu and with the option of triggering the above function. You only need to add this:
function onOpen() {
var ui = SpreadsheetApp.getUi();
ui.createMenu("My Menu")
.addItem("Send Email", "SendEmail")
.addToUi();
}
And this is how it will look like on the Spreadsheet:
Reference
Apps Script Custom Functions;
Apps Script Range Class - isBlank();
Apps Script Custom Menus;
Apps Script Triggers.
I encountered the same problem today "You do not have permission to call MailApp.sendEmail".
I solved this by doing the next steps:
open "Tools" -> "Script editor"
in "Script editor" click on "View" -> "Show manifest file"
open the "appscript.json" file that appeared in the left section of your screen and add "https://www.googleapis.com/auth/script.send_mail" to the oauthScopes, like this:
{
"oauthScopes": ["https://www.googleapis.com/auth/spreadsheets", "https://www.googleapis.com/auth/script.send_mail"],
}
PS: I assigned the script to an image, which basically acts like a button.

How to write Jquery plugin for Google Analytics?

I would like to create a custom plugin for tracking events in my JavaScript Application using Google Analytics Measurement Tool (GA MT), but I am a newbie and not sure how to write such plugin.
My idea about the plugin:
it should have defined all types of events I am going to track (i.e. starting of an application, button clicked, 1st, 2nd, ... slide entered, etc)
if I understand how GA MT works correctly, I will need to specify an event hit for each custom event (see more)
part of the hit parameters (url) is shared (such as version, client ID, tracking ID...)
the other part of the url is custom, so I will store the differences in various functions inside of the plugin
these functions will be later called i.e. on button clicked, on goToNextSlide etc, which will send a hit to GA.
This is an example of my plugin:
(function( $ ) {
var $_document = $(document);
// Shared hit parameters
var hit = 'https://www.google-analytics.com/collect?';
hit += 'v=1'; // Version.
hit += '&t=pageview'; // Pageview hit type.
hit += '&tid=UA-XXXXXX-Y'; // Tracking ID / Property ID.
hit += '&cid=555'; // Client ID.
/* Application opened */
function gacAppOpened() {
console.log('gacAppOpened');
hit += '&dp=%2Fslide-1'; // Page.
httpGetRequest(hit);
}
/* Slide-2 entered */
function gacSlide2() {
console.log('gacSlide2');
hit += '&dp=%2Fslide-2'; // Page.
httpGetRequest(hit);
}
function httpGetRequest( theUrl )
{
var req = new XMLHttpRequest();
req.open("POST", theUrl, true);
req.send(null);
}
}( jQuery ));
This is how I load the plugin (gaCustom.js) and my common JS file (app.js)
<script src="js/gaCustom.js"></script>
<script src="js/app.js"></script>
When trying to reach to my function from inside app.js, I got error (not a function)
goToDefault: function() { // loads first page of my app,
// a hit should be sent to GA about app started
...
gacAppOpened();
... // render template
},
So I am wrong somehow in defining the plugin and using it. I also tried few other attempts, but all of them failed.
I would appreciate to hear whether my approach is good or wrong and what to improve as I am a newbie and would like to do this correctly.

Error: The page has been destroyed and can no longer be used

I'm developing an add-on for the first time. It puts a little widget in the status bar that displays the number of unread Google Reader items. To accommodate this, the add-on process queries the Google Reader API every minute and passes the response to the widget. When I run cfx test I get this error:
Error: The page has been destroyed and can no longer be used.
I made sure to catch the widget's detach event and stop the refresh timer in response, but I'm still seeing the error. What am I doing wrong? Here's the relevant code:
// main.js - Main entry point
const tabs = require('tabs');
const widgets = require('widget');
const data = require('self').data;
const timers = require("timers");
const Request = require("request").Request;
function refreshUnreadCount() {
// Put in Google Reader API request
Request({
url: "https://www.google.com/reader/api/0/unread-count?output=json",
onComplete: function(response) {
// Ignore response if we encountered a 404 (e.g. user isn't logged in)
// or a different HTTP error.
// TODO: Can I make this work when third-party cookies are disabled?
if (response.status == 200) {
monitorWidget.postMessage(response.json);
} else {
monitorWidget.postMessage(null);
}
}
}).get();
}
var monitorWidget = widgets.Widget({
// Mandatory widget ID string
id: "greader-monitor",
// A required string description of the widget used for
// accessibility, title bars, and error reporting.
label: "GReader Monitor",
contentURL: data.url("widget.html"),
contentScriptFile: [data.url("jquery-1.7.2.min.js"), data.url("widget.js")],
onClick: function() {
// Open Google Reader when the widget is clicked.
tabs.open("https://www.google.com/reader/view/");
},
onAttach: function(worker) {
// If the widget's inner width changes, reflect that in the GUI
worker.port.on("widthReported", function(newWidth) {
worker.width = newWidth;
});
var refreshTimer = timers.setInterval(refreshUnreadCount, 60000);
// If the monitor widget is destroyed, make sure the timer gets cancelled.
worker.on("detach", function() {
timers.clearInterval(refreshTimer);
});
refreshUnreadCount();
}
});
// widget.js - Status bar widget script
// Every so often, we'll receive the updated item feed. It's our job
// to parse it.
self.on("message", function(json) {
if (json == null) {
$("span#counter").attr("class", "");
$("span#counter").text("N/A");
} else {
var newTotal = 0;
for (var item in json.unreadcounts) {
newTotal += json.unreadcounts[item].count;
}
// Since the cumulative reading list count is a separate part of the
// unread count info, we have to divide the total by 2.
newTotal /= 2;
$("span#counter").text(newTotal);
// Update style
if (newTotal > 0)
$("span#counter").attr("class", "newitems");
else
$("span#counter").attr("class", "");
}
// Reports the current width of the widget
self.port.emit("widthReported", $("div#widget").width());
});
Edit: I've uploaded the project in its entirety to this GitHub repository.
I think if you use the method monitorWidget.port.emit("widthReported", response.json); you can fire the event. It the second way to communicate with the content script and the add-on script.
Reference for the port communication
Reference for the communication with postMessage
I guess that this message comes up when you call monitorWidget.postMessage() in refreshUnreadCount(). The obvious cause for it would be: while you make sure to call refreshUnreadCount() only when the worker is still active, this function will do an asynchronous request which might take a while. So by the time this request completes the worker might be destroyed already.
One solution would be to pass the worker as a parameter to refreshUnreadCount(). It could then add its own detach listener (remove it when the request is done) and ignore the response if the worker was detached while the request was performed.
function refreshUnreadCount(worker) {
var detached = false;
function onDetach()
{
detached = true;
}
worker.on("detach", onDetach);
Request({
...
onComplete: function(response) {
worker.removeListener("detach", onDetach);
if (detached)
return; // Nothing to update with out data
...
}
}).get();
}
Then again, using try..catch to detect this situation and suppress the error would probably be simpler - but not exactly a clean solution.
I've just seen your message on irc, thanks for reporting your issues.
You are facing some internal bug in the SDK. I've opened a bug about that here.
You should definitely keep the first version of your code, where you send messages to the widget, i.e. widget.postMessage (instead of worker.postMessage). Then we will have to fix the bug I linked to in order to just make your code work!!
Then I suggest you to move the setInterval to the toplevel, otherwise you will fire multiple interval and request, one per window. This attach event is fired for each new firefox window.

Gdata JavaScript Authsub continues redirect

I am using the JavaScript Google Data API and having issues getting the AuthSub script to work correctly. This is my script currently:
google.load('gdata', '1');
function getCookie(c_name){
if(document.cookie.length>0){
c_start=document.cookie.indexOf(c_name + "=");
if(c_start!=-1){
c_start=c_start + c_name.length+1;
c_end=document.cookie.indexOf(";",c_start);
if(c_end==-1) c_end=document.cookie.length;
return unescape(document.cookie.substring(c_start, c_end));
}
}
return "";
}
function main(){
var scope = 'http://www.google.com/calendar/feeds/';
if(!google.accounts.user.checkLogin(scope)){
google.accounts.user.login();
} else {
/*
* Retrieve all calendars
*/
// Create the calendar service object
var calendarService = new google.gdata.calendar.CalendarService('GoogleInc-jsguide-1.0');
// The default "allcalendars" feed is used to retrieve a list of all
// calendars (primary, secondary and subscribed) of the logged-in user
var feedUri = 'http://www.google.com/calendar/feeds/default/allcalendars/full';
// The callback method that will be called when getAllCalendarsFeed() returns feed data
var callback = function(result) {
// Obtain the array of CalendarEntry
var entries = result.feed.entry;
//for (var i = 0; i < entries.length; i++) {
var calendarEntry = entries[0];
var calendarTitle = calendarEntry.getTitle().getText();
alert('Calendar title = ' + calendarTitle);
//}
}
// Error handler to be invoked when getAllCalendarsFeed() produces an error
var handleError = function(error) {
alert(error);
}
// Submit the request using the calendar service object
calendarService.getAllCalendarsFeed(feedUri, callback, handleError);
}
}
google.setOnLoadCallback(main);
However when I run this the page redirects me to the authentication page. After I authenticate it send me back to my page and then quickly sends me back to the authenticate page again. I've included alerts to check if the token is being set and it doesn't seem to be working. Has anyone has this problem?
I was having the same problem so I built this function
function login() {
var scope = "http://www.google.com/calendar/feeds/";
if(!google.accounts.user.checkLogin(scope)) {
if(google.accounts.user.getStatus() == 0) {
var token = google.accounts.user.login();
}
}
}
I added the check to google.accounts.user.getStatus() if it's 1 that means the application is in the process of logging in and if it is 2 that means the applications is logged in. You can also pass a scope to the getStatus method.
the problem is that setting the cookie takes a little while when google redirects back to your site. However, the callback runs immediately, and there is no cookie by that time to verify authentication, so it again redirects back to google. Try using setTimeout or something to run the authentication check after a second or so to be sure.
You should pass the scope to the login method too.
Sometimes you can end up with an orphaned cookie in your browser - which will keep getting fed back to Google.
What I'm doing now, is doing a checkLogin before I perform my login call, and if it returns true I explicitly call logOut().
The logOut call will remove any cookies which Google had rejected but left in your browser. The reason it seems to keep going in a loop is because the cookie is there, but even on reauth, it doesn't produce a new one because you already have one. But unfortunately for our sake, the one that's there is invalid.

Categories

Resources