Reputation: 73
I've got an add-on that previously only targeted Google Docs, and I'm trying to expand the feature set to include Google Sheets. In development mode, I can set a conditional to detect which document type is active (docs or sheets) and then show the corresponding menu. When I publish the latest version of the add-on, the add-on menu stops working in both Docs and Sheets.
I'm guessing it has to do with the permissions around "onOpen()" but i'm not sure how else to handle this. The G Suite Marketplace allows you to designate that an add-on supports multiple editors.
Here's the code that works in development:
function onOpen(e) {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var doc = DocumentApp.getActiveDocument();
if(ss != null && ss != undefined) {
var sheetsUI = SpreadsheetApp.getUi();
sheetsUI.createAddonMenu()
.addItem('Name', 'function')
.addToUi();
}
if(doc != null && doc != undefined) {
var docsUI = DocumentApp.getUi();
docsUI.createAddonMenu()
.addItem('Name', 'function')
.addToUi();
}
}
If I remove the conditional stuff, and only include editor specific menu (docs for docs, sheets for sheets), the menus appear correctly.
Upvotes: 1
Views: 447
Reputation: 31300
You wouldn't want the user to need to approve access to their Sheets, if it's a Docs add-on and vice versa. And if the add-on doesn't have permission to one of them then your code would throw an error, so you need to trap the error with a try/catch
function onOpen(e) {
var docUI,thisIsA_Sheet;
try{
docUI = SpreadsheetApp.getUi();
thisIsA_Sheet = true;
}catch(e){
//Do nothing
}
if (!thisIsA_Sheet) {//This is not a Google Sheet
try{
docUI = DocumentApp.getUi();
}catch(e){
//Do nothing
}
}
docUI.createAddonMenu()
.addItem('Name', 'function')
.addToUi();
}
Upvotes: 1
Reputation: 73
The comment about trapping errors led me to the solution. I placed each editor's menu code inside try/catch blocks, and now it works.
function onOpen(e) {
try{
var docsUI = SpreadsheetApp.getUi();
docsUI.createAddonMenu()
.addItem('Sheets menu item name', 'function')
.addToUi();
} catch(e) {
}
try{
var docsUI = DocumentApp.getUi();
docsUI.createAddonMenu()
.addItem('Docs menu item name', 'function')
.addToUi();
} catch(e) {
}
}
Upvotes: 1