Gmail Apps script function to display Browser MsgBox from GMail Addon - javascript

I have the following working code which validates a list of recipients based on specific conditions. However, I'm looking to replace the resulting "Logger.log" actions with "Browser.msgbox" actions, and for some reason, GMail App Addons are not allowing me to do so:
function validateRecipients(e) {
var toEmails = e.draftMetadata.toRecipients, ccEmails = e.draftMetadata.ccRecipients, bccEmails = e.draftMetadata.bccRecipients, domains = [], uniqueDomains = [];
var allEmails = toEmails.concat(ccEmails, bccEmails);
for (var i = 0; i < allEmails.length; i++) {
domains[i] = allEmails[i].split("#").pop().split(".")[0];
}
uniqueDomains = domains.filter(listUnique);
if(uniqueDomains.length <= 2 && uniqueDomains.indexOf("verasafe") != -1) {
Logger.log("This Message is Good to Go");
}
else if(uniqueDomains.length == 0) {
Logger.log("This Message has no recipients");
}
else {
Logger.log("Please Validate Receipients of this Message and Try again");
}
}

Partial answer
Browser.msg can't be used on Gmail Add-ons, because, from https://developers.google.com/apps-script/reference/base/browser
This class provides access to dialog boxes specific to Google Sheets.

You cannot use Browser.msg or any of the UI classes with Gmail.
However, there is a new feature called Card Service that is meant to be used for the creation of UI for Gmail Addons.
Hope this helps!

The closest I could currently find is notification which shows a quick message at the bottom of the card (in Google's Material design it's called a snackbar
https://developers.google.com/apps-script/reference/card-service/notification
Other than that you need to replace the card with a new one.
function _navigateToCard(card: GoogleAppsScript.Card_Service.Card, replace: boolean)
{
var nav = CardService.newNavigation();
replace ? nav.updateCard(card) : nav.pushCard(card)
return CardService.newActionResponseBuilder()
.setNavigation(nav)
.build();
}

Related

Trying to pull user email when they check a checkbox

I am trying to pull an active user's email when they check a box. I wish to paste the active user's email in a separate column (adjacent currently, but the ability to be flexible would be nice). I have done this before in a different worksheet, but for some reason I cannot get it to work on this one. I can get it to paste a simple variable, or even the edit date, so I am thinking there must be something erroring out with the user specifically. I am on a work owned domain with company addresses, but so is the other sheet that is working. Anyway, here is what I have currently (amature, be gentle):
function onEditAdded(e) {
var activeSheet = e.source.getActiveSheet();
if (activeSheet.getName() == "New Hires") {
var aCell = e.source.getActiveCell(), col = aCell.getColumn();
if (col == 20) {
var dateCell = aCell.offset(0,1);
if (aCell.getValue() === true) {
var email = Session.getActiveUser().getEmail();
Logger.log(email);
dateCell.setValue(email);
} else {
dateCell.setValue("");
}
}
}
}
I test your code and it should run without issues.
You just need to add it as an Installable Triggers
Manually create installable trigger:
Open your Apps Script project.
click Triggers alarm.
At the bottom right, click Add Trigger.
Select and configure the type of trigger you want to create.
Click Save.
function onEditAdded(e) {
var activeSheet = e.source.getActiveSheet();
if (activeSheet.getName() == "New Hires") {
var aCell = e.source.getActiveCell(), col = aCell.getColumn();
if (col == 1) {
var dateCell = aCell.offset(0,1);
if (aCell.getValue() === true) {
var email = Session.getActiveUser().getEmail();
Logger.log(email);
dateCell.setValue('user#example.com');
} else {
dateCell.setValue("");
}
}
}
}
Output:
You can also explore on how to create installable triggers programmatically, so that you wont need to add it manually every time you copy this script to a different workbook.
References:
https://developers.google.com/apps-script/guides/triggers/installable#managing_triggers_programmatically
Is there any way to automatically create installable triggers?

Passing Information to a Trusted Web Activity using Query Parameters

I have created a Trusted Web Activity. In order to hide some html content i have modified "startUrl": "/?utm_source=trusted-web-activity".
I check for this query param and i save it in sessionStorage ( i dont use localStorage because it is shared with all tabs).
Based on the existence of this params i display or hide some divs :
if(sessionStorage.getItem('activity')) {
document.getElementById( 'mobile_navigation' ).style.display = 'block'; }
Everything is working as is expected. The only problem is that if i keep the app in background for a while and i open it the page is reloaded and all the rules dont work anymore. I have even tried to populate a field and to get it from here.
const queryString = window.location.search;
const urlParams = new URLSearchParams(queryString);
trustewdweb = urlParams.get('utm_source');
let fields = document.getElementById("fields");
if (trustewdweb === 'trusted-web-activity'){
fields.value = trustewdweb;}
if(!sessionStorage.getItem('activity')) {
populateStorage();
} else {
populateField();
}
function populateStorage() {
sessionStorage.setItem('activity', document.getElementById('fields').value);
populateField();
}
function populateField() {
var currentQuery = sessionStorage.getItem('activity');
document.getElementById('fields').value = currentQuery ;
}
if(sessionStorage.getItem('activity')) {
How can i avoid this behaviour? It is related to cache?

Creating whole new view based on current user's group sharepoint 2013

I am trying to generate a view based on the current user's group name. Group Name I am gathering from the custom list.
My question is how to apply the gathered group name to 'Group Name' column as a view parameter.
The only solution I figured:
I have created a view with a parameter.
I have added an HTML Form Web Part into the same page and connected it to the list view (sending the value to the parameter via web part connection). Then with a window.onload function I gather the current user's group name and pass this value via Form Postback function. But since the Postback function triggers full page reload, it falls into the endless loop of form submission > page reload.
Another way I have tried is attaching a click event listener to the BY MY GROUPS tab and it works perfectly, but the only disadvantage is that the page reloads each time user clicks on this tab, which I would like to avoid.
So the solution that I need is a way to post the form without a page reload.
Another option suggested here is to use CSR (client side rendering), but that has its own problems:
This code does not work as it is supposed to. In the console it shows me correct items, but the view appears untouchable.
Even if it worked, the other column values are still viewable in the column filter, as in this screenshot:
So, it seems that CSR just hides items from the view (and they are still available). In other words its behavior is different from, for example, a CAML query.
Or am I getting it wrong and there's something wrong with my code?
Below you can find my CSR code:
<script type='text/javascript'>
(function() {
function listPreRender(renderCtx) {
SP.SOD.executeFunc('sp.js', 'SP.ClientContext', function() {
var currUserID = _spPageContextInfo.userId;
var cx = new SP.ClientContext('/sites/support');
var list = cx.get_web().get_lists().getByTitle('Group Members');
var items = list.getItems(SP.CamlQuery.createAllItemsQuery());
cx.load(items, 'Include(_x006e_x50,DepID)');
cx.executeQueryAsync(
function() {
var i = items.get_count();
while (i--) {
var item = items.getItemAtIndex(i);
var userID = item.get_item('_x006e_x50').get_lookupId();
var group = item.get_item('DepID').get_lookupValue();
if (currUserID === userID) {
var rows = renderCtx.ListData.Row;
var customView = [];
var i = rows.length;
while (i--) {
var show = rows[i]['Group_x0020_Name'] === group;
if (show) {
customView.push(rows[i]);
}
}
renderCtx.ListData.Row = customView;
renderCtx.ListData.LastRow = customView.length;
console.log(JSON.stringify(renderCtx.ListData.Row));
break;
}
}
},
function() {
alert('Something went wrong. Please contact developer')
}
);
});
}
function registerListRenderer() {
var context = {};
context.Templates = {};
context.OnPreRender = listPreRender;
SPClientTemplates.TemplateManager.RegisterTemplateOverrides(context);
}
ExecuteOrDelayUntilScriptLoaded(registerListRenderer, 'clienttemplates.js');
})();
</script>

How to toggle Firefox responsive design view resolution through code

I am switching on the firefox responsive design view from my xul based addon with the following code.
var mytmp = {};
Cu.import("resource://gre/modules/Services.jsm");
Services.prefs.setCharPref("devtools.responsiveUI.presets", JSON.stringify([{name:'tmp1', key: "234x899", width:300,height:300}]));
Cu.import("resource:///modules/devtools/responsivedesign.jsm", mytmp);
var win = window.bridge.myWindow;
mytmp.ResponsiveUIManager.toggle(win, win.gBrowser.tabContainer.childNodes[0]);
Following is the code which toggles the resolution
this.menulist.addEventListener("select", this.bound_presetSelected, true);
/**
* When a preset is selected, apply it.
*/
presetSelected: function RUI_presetSelected() {
if (this.menulist.selectedItem.getAttribute("ispreset") === "true") {
this.selectedItem = this.menulist.selectedItem;
this.rotateValue = false;
let selectedPreset = this.menuitems.get(this.selectedItem);
this.loadPreset(selectedPreset);
this.currentPresetKey = selectedPreset.key;
this.saveCurrentPreset();
// Update the buttons hidden status according to the new selected preset
if (selectedPreset == this.customPreset) {
this.addbutton.hidden = false;
this.removebutton.hidden = true;
} else {
this.addbutton.hidden = true;
this.removebutton.hidden = false;
}
}
},
I tried to access the menulist and do a event trigger myself but couldn't access it. How do I select the dropdown?
paa's answer does work but it creates a new custom entry in the screen presets but doesnt select an existing one. You can do so by triggering a click event on the preset select ui.
Like this
var win = window.bridge.myWindow;
var i = 3 // index of the preset to be selected
var responsiveUI= win.gBrowser.selectedTab.__responsiveUI;
$(responsiveUI.menulist.children[0].children[i]).trigger('click');
Assuming the responsive UI is turned on
gBrowser.selectedTab.__responsiveUI.setSize(320,480);
update:
I took as granted that you want to set an arbitrary size, but you actually ask about the presets. Is this still a valid answer?

Execute javascript only in specific url

I have an external JS file with inside this code:
var mobile_number_param = document.getElementById('mobile_number_param');
mobile_number_param.maxLength = 9;
mobile_number_param.readOnly = true;
var email = document.getElementById('email');
email.readOnly = true;
var user_notes = document.getElementById('user_notes');
user_notes.maxLength = 90;
var admin_notes = document.getElementById('admin_notes');
admin_notes.maxLength = 90;
Now my goal is to apply the code related to "mobile_number_param" but ONLY when I'm on the "reserve.php" page otherwise I'm not allowed to modify my Mobile Phone number in other area such my profile page.
Somebody told me this:
You can recognize the current url by checking window.location.href and e.g. searching for reserve.php to know you're on the reservation page..then apply your code.
Unfortunately I'm not a coder and don't have any idea how to do.
Any suggestions ? Thank for your time...
if (window.location.href.indexOf('reserve.php') != -1) {
// do stuff for reserve.php page here
}
Just add the following function in your external JS File:
function myFunction(pagename) {
var pageurl = window.location.href;
var pg = pageurl.split("/"); /*SPLITS THE URL ACCORDING TO DELIMINATOR "/". Eg x/y/z/reserve.php pg[0]=x,..pg[3]=reserve.php*/
var pgname = (pg[pg.length - 1]);
if (pagename == pgname) /*check whether the current page is reserve.php or not*/
{
return true;
}
return false;
}
Calling the Function:
if (myFunction("reserve.php")) {
/*Yes reserve.php page*/
} else {
/*Not reserve.php page*/
}
Server sided you could read the HTTP referer field.
If it contains reserve.php include the one js else an other js.
If you prefer to use only one js you could wrap the fucionality into a function.
called from reserve.php with parameter 1, from other pages parameter 0
or else.

Categories

Resources