Reputation: 147
I'am using Google App Script and Google Spreadsheet onOpen() trigger. I'm locking logged in user in Google Spreadsheet.
The restriction for the same is that it's not logging email id on cross domain which I found on forums.
Here is the code for the same:
function onOpen(e)
{
try
{
var ui = SpreadsheetApp.getUi();
ui.createMenu('Action')
.addItem('Add Data', 'addData')
.addToUi()
var sheet =SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Login Details");
sheet.appendRow([Session.getActiveUser().getEmail(),new Date()]);
}
catch(e)
{
Logger.log(e);
}
}
One observation from onOpen() functionality :
1] I'm owner of spreadsheet and it only logs the email ids of our company domain. (Automatically onOpen() of spreadsheet)
2] From other domain when I open bounded script of spreadsheet and run onOpen() then it logs the logged in user.
What is reason behind the same and is there any workaround for user on cross domain?
Upvotes: 1
Views: 2766
Reputation: 912
I think Session.getActiveUser().getEmail()
has issues with onOpen trigger on outside domain when that person is not the owner.
Also, automatic per minute triggers also are not able to log active user.
Here's the workaround:
Add menu in the spreadsheet itself, with an option which when clicked, will run the function to append the row that you want. As, Session.getActiveUser().getEmail()
is working when we run function manually from script.
Use this code:
function addMenu()
{
var ui = SpreadsheetApp.getUi();
ui.createMenu('Log user')
.addItem('Run script', 'appendRow')
.addToUi()
}
And also add this function:
function appendRow()
{
SpreadsheetApp.getActiveSpreadsheet().getSheetByName("YOUR_SHEET").appendRow([Session.getActiveUser().getEmail(),new Date()]);
}
Now, whenever you want to log the active user, go to that Log user and click Run script and it will append the row.
Also, don't forget to set onOpen trigger for addMenu() function on client side or even your side.
For more details, we can read this: Class session
Upvotes: 1