JavaScript Objects Quick Reference

Any object in JavaScript is a collection of key-value pairs. The key, also known as a property, is a unique string that maps to a value which may be a Boolean, String or another object.

Let’s take a simple person object that contains properties like name, age and the employment status.

const person = {
  name: 'John',
  age: 21,
  gender: 'Male',
  employed: false,
};
  • Check if a property (or key) exists in an object
console.log('country' in person); // returns false
console.log('employed' in person); // returns true
console.log(person.hasOwnProperty('gender'));
  • Iterate over an object and print the key-value pairs
Object.keys(person).forEach((key) => {
  console.log(`${key}: ${person[key]}`);
});

Object.entries(person).forEach(([key, value]) => {
  console.log(`${key}: ${value}`);
});
  • Prevent new properties from being added to the object
Object.preventExtensions(person);
person.full_name = 'John Q Public';
console.log(person); // the full name property is not added
  • Check if new properties can be added to an object
Object.isExtensible(person);
delete person.name; // you can still delete properties
  • Prevent properties from getting added or deleted
Object.seal(person);
delete person.age;
console.log(person.age); // the property is not deleted
  • Check if properties can be added or deleted from any object
Object.isSealed(person);
  • Prevent properties from getting added, deleted or modified
Object.freeze(person);
  • Check if an object can be modified
Object.isFrozen(person);
  • Combine two objects (use default values)
const defaultPerson = {
  name: 'Unknown',
  country: 'Unknown',
};

const newPerson = {
  name: 'John',
  age: 21,
};

const mergedPerson = Object.assign(defaultPerson, newPerson);
console.log(mergedPerson);
  • Create a shallow clone of an object
const clone = Object.assign({}, person);
// changes to the clone will not modify the original object

How to Play YouTube Videos at Custom Speed

The settings pane in the YouTube video player lets you quickly change the default playback speed of the current video. You may go as high as 2x that will play the video at twice the normal speed. The lower limit is 0.25 that will slow down the video to one-fourth the original speed.

Change YouTube Video Speed

Watch YouTube at Custom Speed

YouTube allows you to play videos at 2x the original speed but what if you want to speed up and watch videos at an even higher speed - like 4x or 10x the normal speed?

That’s where Chrome Developer Tools can help.

Open any YouTube video inside Google Chrome and launch the JavaScript console from the Chrome menu bar. Go to the View menu, choose Developer, and select JavaScript console from the sub-menu.

Inside the console window, type the following command and it will instantly change the playback speed of the current video to 8x the normal speed.

$('video').playbackRate = 8;

If you want to slow down a video, try a value lower than 1 as:

$('video').playbackRate = 0.125;

You may set the playback speed to any value between 0.0625 and 16. This is the allowed range of media playback rate in Chrome.

Also see: Embed Lightweight YouTube Player

Build a COVID-19 Self Assessment Tool with Google Forms

Businesses and schools worldwide are using Google Forms to build COVID-19 self-declaration forms that employees, students and visitors must complete every day before they can attend work. Here is a sample COVID-19 Health Screening Form - if the answer is “yes” to any of the questions, the person is expected to stay home.

COVID-19 Google Form

After a respondent submits the form, a confirmation email is sent to them instantly with the Email Notifications add-on. The email is like a clearance certificate detailing whether the person can attend work or not. If they are allowed entry, the email also contains a dynamic QR Code that can be scanned and verified at the entry point.

Send Conditional Notification Emails

The conditional notifications feature of the Google Forms add-on automatically determines if the respondent should be sent the “Allowed to enter premises” email or not. It looks at the form’s answers and compares them with the specified criteria to make this choice.

COVID-19 Health Screening Questionnaire

For instance, if the employee has entered a value greater than 100.4 in the temperature field, they are sent the “Work from home” email. Similarly, they are not allowed to attend work if they selected any value other than “None of the above” for the symptoms question.

To enable this workflow with Google Forms, you are required to create two email rules - one rule for employees that have passed the self-assessment test and the other rule for people who are required to work from home based on their self-assessment.

Rule 1: Allowed to Attend Work

Create a new rule for the respondents and set the conditional notifications as shown in the screenshot.

Allowed to Attend Office

You can put {{Email Address}} in the email field and this will be replaced with the respondent’s email address that is submitted in the form entry. If you have a Google Form that is restricted to your school or organization, the email address of the submitter will be automatically recorded in the form entry.

For the email template, you can use the QR Code function that will add a dynamic image in the outgoing email with the form answers.

Email Template

Rule 2: Work from Home

To save time, duplicate the previous rule and edit the conditional notification to send a different email to people who aren’t considered fit to attend office and should continue working from home.

If you compare this conditional logic screen with the previous one, you’ll notice that it uses OR instead of AND with different criteria indicating that if either of the conditions is true, the email should be sent.

Any condition matches

Demo Check-in Google Form

If you would like to test this self-assessment tool, fill this COVID-19 Google Form and you’ll receive an instant confirmation email with the result. Here’s a copy of the email sent by the Google Form when the respondent passes the self-assessment.

Check the Form Notifications user guide to learn more about the features of the add-on.

Generate firebase.json file for Firebase Redirects

We recently moved the user guide for Mail Merge and Form Notifications from the website labnol.org to digitalinspiration.com. As with any domain move, we had to manually setup 301 redirects so that the audience are automatically redirected to the new website should they happen to click any of the links that still point to the old domain.

Because the websites are hosted on Firebase, it is easy to setup 301 redirects through the firebase.json file. All we need are entries in the redirects array, one entry per redirect, specifying the source, the destination URL and it is also possible to define if the redirect is 301 (permanent) or a temporary 302 redirect.

{
  "redirects": [
    {
      "source": "/page1",
      "destination": "https://digitalinspiration.com/page1",
      "type": 301
    },
    {
      "source": "/page2{,/**}", // also redirect pages ending with slash
      "destination": "https://digitalinspiration.com/page2",
      "type": 302
    }
  ]
}

When you are migrating big sites, it can become difficult to maintain the firebase.json file as 100s of URLs that may have to added in the redirects array. As as workaround, you can create a separate JSON file with all the redirects and then generate the firebase.json file dynamically.

The firebase file is generated automatically from the redirects file before the assets are uploaded to Firebase hosting.

Step 1: Create a base file firebase.base.json. As you can see, we have a few redirects setup already and the new redirect entries will be merged into this array.

{
  "hosting": {
    "public": "public",
    "ignore": ["firebase.json", "**/.*", "**/node_modules/**"],
    "redirects": [
      {
        "source": "/foo{,/**}",
        "destination": "/bar",
        "type": 301
      },
      {
        "source": "/firebase/**",
        "destination": "https://firebase.google.com/",
        "type": 302
      }
    ]
  }
}

Step 2: Create a firebase.redirects.json file with the links property that contains an array of links. Each link entry will have the source regex pattern or glob, the description URL and the type of redirect (optional).

{
  "links": [
    [
      "/email-google-form-responses-7263",
      "https://digitalinspiration.com/docs/form-notifications/email-multiple-people"
    ],
    [
      "/embed-qrcode-barcode-google-forms-021020",
      "https://digitalinspiration.com/docs/form-notifications/barcode-qrcode"
    ],
    [
      "/internet/google-forms-mobile-notifications/29203",
      "https://digitalinspiration.com/docs/form-notifications/phone-push-notifications",
      false
    ]
  ]
}

Step 3: Create a generate.js that will read the the base file and generate a new firebase.json file using redirects listed in the redirects.json file. All

const fs = require('fs');

const redirects = fs.readFileSync('firebase.redirects.json');
const { links = [] } = JSON.parse(redirects);

const linkMap = links.map((link) => {
  const [source, destination, permanent = true] = link;
  return {
    source: `${source}{,/**}`,
    destination,
    type: permanent ? 301 : 302,
  };
});

const firebase = fs.readFileSync('firebase.base.json');

const file = JSON.parse(firebase);

file.hosting.redirects = [...file.hosting.redirects, ...linkMap];

fs.writeFileSync('firebase.json', JSON.stringify(file, null, 2));

Step 4: Inside the package.json file, add a new entry in the script section to generate the file before the upload step.

{
  "scripts": {
    "generator": "node generate.js",
    "upload": "npm run generator && firebase deploy --only hosting"
  }
}

This will ensure that a new firebase.json file is regenerated before deployment.

How to Change the Reply-to Address in Mail Merge

When you send an email campaign through Gmail, you’ve an option to specify a different reply-to email address for your emails. When the email recipient hits the “Reply” or “Reply All” button, the To field in their email reply will be automatically populated with the email address that you’ve specified as the Reply-to email at the time of sending.

You can even specify more than one email addresses in the reply-to field, separated by commas, and they will all show up in the To field of the reply field. For instance, you could send emails from your own email address but the replies would be received in your email inbox as well as the support team.

To get started, open your Google sheet, go to the add-ons menu and choose Mail merge with attachments.

Next click on the Configure menu to open the Mail Merge sidebar.

Change Reply-to Email address

Here go the Reply-to address file and type an email address. If you wish to receive replies on multiple email addresses, type them all here separated by commas.

Now when you send the email campaign, open one of the emails in the sent items folder, expand the message header and you should see the specified email addresses listed in the reply-to field.

Different Reply-to address

Why is Google Ignoring the Reply-to Address

If you send a test email to yourself, you’ll get the email in your inbox. If you hit the reply button in that message, you may notice that that reply-to field contains your own email address and not the custom email address(es) that you’ve specified in your mail merge.

That’s the default behavior in Gmail if the “from” address on an email message is the same as the “to” address or is one of your own email aliases. To test your reply-to functionality, you should send emails to an email address that is not connected to your current Gmail account or set the “From” address as a non-Gmail address.

Download Gmail Messages as EML Files in Google Drive

This Google Script will help you download your email messages from Gmail to your Google Drive in the EML format.

What is the EML Format

The .eml file format is popular for transferring emails from one email program to another since it complies with the RFC 822 standard and thus can be natively opened inside Apple Mail and Microsoft Outlook. You can even open EML files inside Google Chrome by dragging the file from your desktop onto a new browser table.

EML files contains the email content (email body, header and encoded images and attachments) as plain text in MIME format.

Download Gmail message as EML Files

Inside Gmail, open any email thread, go to the 3-dot menu and choose “Download Message” from the menu. It will turn your current email message into an eml file and save it your desktop.

However, if you wish to automate the process and download multiple emails as eml files in your Google Drive, Apps Script can help.

const downloadEmails = () => {
  const sender = 'sender@domain.com';
  const threads = GmailApp.search(`from:${sender}`).slice(0, 10);
  threads.forEach((thread) => {
    const subject = thread.getFirstMessageSubject();
    const [message] = thread.getMessages();
    const rawContent = message.getRawContent();
    const blob = Utilities.newBlob(rawContent, null, `${subject}.eml`);
    const file = DriveApp.createFile(blob);
    Logger.log(subject, file.getUrl());
  });
};

The script searches for emails from the specified sender, gets the first email message and downloads it your Google Drive.

Forward Gmail as EML Attachment

If you are to forward an email message as an attachment, the .eml format may be recommended since it preserves all the formatting and attachments of the original email thread in a single file that can be attached to the email.

const forwardEmail = () => {
  const messageId = '123';
  const message = GmailApp.getMessageById(messageId);
  const rawContent = message.getRawContent();
  const blob = Utilities.newBlob(rawContent, null, `email.eml`);
  GmailApp.sendEmail('to@gmail.com', 'This email contains an eml file', '', {
    attachments: [blob],
  });
};

Also see: Download Gmail as PDF Files

Google Drive Monitor – Get Email Alerts When Files are Deleted in your Drive

When you delete a file in Google Drive, it moves to the trash folder and stays there indefinitely until you manually empty the bin. That is how it has always been but, sometime this month, Google made one important change to how the trash bin works.

Under the new policy, files that have been in Google Drive’s trash bin for more than 30-days are automatically deleted. This automatic cleanup does help reclaim space but if you happen to accidentally delete some important files or folders from your Google Drive, there’s no way to restore them from the trash after the 30-day window.

Monitor Google Drive Files

If you are like me who is terrified at the prospect of forever losing important files that were deleted by mistake, Google Drive Watch can help.

Google Drive Watch is an open-source Google Script that automatically monitors your Google Drive and sends daily email notifications with a detailed list of files that were deleted the previous day.

Here’s a sample email notification sent by the Google Drive Watch program.

Google Drive Watch Deleted Files

The email includes the file link, the date when the file was first created, and the name/email address of the Google Account that last modified and deleted the file. It monitors files in your regular Google Drive as well as Shared Drive folders.

Watch your own Google Drive

Here’s how you can set up Google Drive watch for your own Google account in few easy steps:

  1. Click here to make a copy of the Google script in your own Google Drive.

  2. Inside the script editor, go to line #9 and specify the email address where you want to receive the Drive notifications. You can also put multiple emails separated by commas.

  3. The script, by default, will create a cron job that will run once per day at the selected hour. If you however wish to change the frequency so that the notifications arrive, say, every 5 days, you can specify 5 in line #10.

  4. We are almost there. Go to the Run menu and choose “Enable Drive Watch” to enable the monitor for your Drive. Allow the script to access your file and you are all set.

Configure Google Drive Watch Email

Important: The first email notification will only arrive the next day at the selected hour.

How Google Drive Monitoring Works

The source code of the Google Drive monitor script is available on Github.

Internally, the script uses the Google Drive API with Google Apps Script to watch for changes in your Google Drive. It then sets up a daily cron job, using triggers in Google Scripts, that sends the email if new file changes are found.

When you first run the script, it gets a starting page token and all changes made to Google Drive after this token is fetched will be monitored by the script. We set supportsAllDrives to true since the script should monitor folders in Team Drives as well.

function getPageToken() {
  const store = PropertiesService.getScriptProperties();
  const token = store.getProperty('token');
  if (token) return token;
  const { startPageToken } = Drive.Changes.getStartPageToken({
    supportsAllDrives: true,
  });
  store.setProperty('token', startPageToken);
  return startPageToken;
}

The change.list endpoint of the Google Drive API fetches all changes made to the authorized user’s Drive since the start page token. We also set the fields property to limit file properties that are available in the response. The newStartPageToken returned in the response will become the new page token for future calls to the Drive API.

const fields = `newStartPageToken,
  items(file(id,title,labels(trashed),
  iconLink,mimeType,createdDate,ownedByMe,
  lastModifyingUser(emailAddress,displayName,picture(url)),
  alternateLink, fileSize))`;

const { newStartPageToken, items = [] } = Drive.Changes.list({
  fields,
  pageToken: getPageToken(),
  includeItemsFromAllDrives: true,
  pageSize: 100,
  supportsAllDrives: true,
});

if (newStartPageToken) {
  propertyStore.setProperty('token', newStartPageToken);
}

The items array holds a list of files that have been modified since the last run. This also includes new files that have added and old files that were edited by the users. Since we are only interested in the file that have been trashed, we’ll filter all files from the response except the ones that have been trashed.

const filteredItems = items
  .map(({ file }) => file)
  // Only interested in files where "I" am the owner
  .filter(({ ownedByMe }) => ownedByMe)
  // Only interested in files that have been "trashed"
  .filter(({ labels: { trashed } = {} }) => trashed === true)
  // Only return fields that are sent by email
  .map((file) => {
    const {
      iconLink,
      alternateLink,
      title,
      lastModifyingUser = {},
      createdDate,
      fileSize,
    } = file;
    return { iconLink, alternateLink, title, createdDate, fileSize };
  });

Now that we have an array of files that have been deleted by the user since the last run, we can use the Gmail service to notify the user.

Also see: Google Drive URL Tricks

How to Search Emails in Gmail by Specific Time

Gmail supports a plethora of search operators to help you instantly find that elusive email message buried in your mailbox. You have size search - like larger_than:5mb - to find the big messages in your account. File search - like has:attachment filename:doc - will locate email messages that contain specific file attachments. This graphic illustrates all the known Gmail search operators that work both on Gmail website and mobile.

Gmail Search Tricks

Search by Date in Gmail

Date search in Gmail helps you locate emails sent or received during a specific period. Here are some examples:

  • newer_than:7d from:me - Emails sent in the last 7 days
  • after:2020/10/15 before:2020/10/20 from:uber - Emails from Uber received between October 15 and October 20.
  • newer_than:60d older_than:30d - All emails received in the previous 30-day range.

The date in the Gmail search query is specified in the YYYY/MM/DD format.

Search Emails by Specific Time in Gmail

Gmail supports an undocumented time-based search option that lets you find emails sent or received during a specific hour, minute or event second. For instance, you can limit your Gmail search to emails that were received between October 10 8:15 PM and October 10, 2020 8:45 PM.

Gmail Search Date and Time

To get started, convert the date and time to Epoch time and then use the timestamp with the standard after or before search operator of Gmail.

For instance, the Epoch time for October 10 8:30 PM is 1602774000 and that of October 10 8:45 PM is 1602774900. Use the search query after:1602774000 before:1602774900 to:me in Gmail and you’ll get a list of all emails that were received during that 15-minute period.

Epoch time is the number of seconds that have elapsed since January 1, 1970 (UTC). Use the Epoch converter to represent a human readable date and time in Epoch and use that timestamp with the before or after search operator of Gmail to find that elusive email.

Date and Time Search with Google Script

Here’s a little snippet that will automate your Gmail search by time using the Gmail API. It will fetch all email messages that were received between 12:15 PM and 1:30 PM.

const emailReceived = () => {
  const secondsSinceEpoch = (date) => Math.floor(date.getTime() / 1000);
  const after = new Date();
  const before = new Date();
  after.setHours(12, 15, 0, 0);
  before.setHours(13, 30, 0, 0);
  const query = `after:${secondsSinceEpoch(after)} before:${secondsSinceEpoch(
    before
  )}`;
  const messages = Gmail.Users.Messages.list('me', {
    q: query,
  });
  Logger.log(messages);
};

Also see: Mail Merge for Gmail

How to Send Emails from a Different Address (Alias) with Gmail

Say you have two email accounts - personal@gmail.com and work@company.com - the former is your personal email address while the latter is your work (corporate) email address. You are logged into your personal Gmail account but would like the mail merge to go out from your work account.

Consider another scenario where the personal secretary needs to sends out emails on behalf of her boss. So she runs the merge while staying logged into her own Google account but the recipients will see her boss’s email as the sender.

Both these scenarios can be easily handled in Mail Merge and Document Studio by setting up aliases in Gmail.

You can even send emails from your Outlook, Yahoo or Zoho email addresses through aliases in Gmail. Students and teach can send emails from their @school.edu email address while logged into their personal email accounts.

How to Setup Email Aliases in Gmail

Open gmail.com on your desktop computer, go to Settings, click the Accounts tab and, under the “Send mail as” section, click the link that says “Add another email address.”

Gmail Add Email Address

Next, follow the wizard to add the other email address as an alias to your current email address. You need to specify the sender’s name, the email address on behalf of which you wish to send out th emails and the reply-to address (optional).

Gmail Alias Setting

Treat as an alias - Yes or No?

If you own both email accounts, check the “treat as alias” option and emails sent to either address will arrive in the same Gmail inbox.

If you are sending emails on behalf on another person, say a secretary sending emails on behalf of his or her boss, the option should be unchecked. When the recipient replies to messages you send from the alias, the To: field in their reply message will be filled with your alias email address.

Gmail Verification

Gmail will send a verification code to your other email address that you wish to add as an alias to verify whether you really own or have access to that email account.

Verification Email Link

Log in to your other Gmail account and open confirmation email. Copy the confirmation code and paste it into alias verification box. Your other email address will now be added as an alias to your primary email address.

Change the Email Sender

This is how you can send emails from a different address in Google Sheets.

Mail Merge for Gmail

Send Email from Alias

Open your Google Sheet, choose Addons > Mail Merge with Attachments > Configure to open the merge sidebar. Expand the “Sender’s Email” dropdown and it will have a list of all email aliases that are connected to your Gmail account.

You can now send personalized emails on behalf of any email address that you own or have verified as an alias.

Document Studio

Open Google Sheet, go to Add-ons > Document Studio > Open. Expand the Mail Merge section and click on edit to open the Email Template designer. You’ll have an option to change the email sender as shown in the screenshot below:

Change Email Sender

Error - Cannot Add Aliases in Gmail

Are you getting an error while adding an alias in Gmail?

You must send through gmail.com SMTP servers you can send as abc@work.com. However, this functionality is not available for your account. Please contact your domain administrator.

If you do not see an option to add aliases in your Gmail settings, it is likely because your Google Workspace (GSuite) domain administrator has disabled the option to send email from aliases in domain settings.

To enable email sender aliases in Google Works, ask the admin to:

  1. Sign into the Google Admin console admin.google.com.
  2. From the dashboard, go to Apps > GSuite > Gmail > End User Access.
  3. Turn on the “Allow per-user outbound gateways” setting that says “Allow users to send mail through an external SMTP server when configuring a “from” address hosted outside your email domains.”

Save the settings and wait for about 30-60 minutes for the changes to propagate. You’ll then be able to added external email addresses as aliases in your Google Workspace email account.

Google Workspace Email Setting Send from a different email address in Google Workspace

How to Embed Barcode and QR Code In Google Forms Notifications

The Google Form Notifications add-on lets you automatically send Google Form responses in an email message to one or more recipients. The email notifications are dispatched the moment your form receives a new submission.

The more recent version of the Google Form addon includes support for QR Code and Barcode symbols that you can embed in the email messages. The images can be generated from static text or you can create dynamic images based on answers submitted by the user.

Add QR Code images in Emails

The basic syntax for adding QR Code images in emails is:

=QRCODE(Your Text Goes Here)

You can customize the colors and size of the QR code image by adding key-value pairs in the QRCODE function.

For instance, if you would like the QRCode to have Indigo background and the QRCode should be itself in white color, the modified formula with the hex color codes would be:

=QRCODE(TEXT textcolor=#FFFFFF backgroundcolor=#4B0082)

The QR Code images have a default width of 300px but if you customize the size with the width parameter as shown below:

=QRCODE(TEXT width=225)

Insert QR Code in Google Form

Include dynamic text in QR Code images

Until now, we have seen examples of static text but the Google Forms addon can also create QR Code images from text in Google Form Answers using placeholders.

For instance, if your Google has a question title “What is your website address?”, you can use a QR Code function like the one below. This will turn the user’s answer into a dynamic QR code that, on scanning, will take you to the form respondent’s website.

=QRCODE({{WWhat is your website address}} textcolor=#4B0082)

Embed Barcode in Email Notifications

The Email Notifications add-on also includes support for BARCODE function to help you embed barcode images in PNG format for EAN, UPC, ISBN, postal codes, GS1 Database and all other popular formats.

The basic syntax for barcode function is:

=BARCODE(TEXT format=CODE39)

For instance, if you would like to embed the barcode image for a book whose ISBN-13 code is 9781786330895, the function would be:

=BARCODE(9781786330895 format=EAN13 includetext=true)

The includetext=true parameter would ensure that the text for data is included into the barcode image.

Insert Barcode symbol in Google Form

You can also modify the colors of barcode image using hex codes:

=BARCODE(9781786330895 format=EAN13 includetext=true barcolor=AA0000 textcolor=008888 backgroundcolor=FFFF60)

You can similarly modify the width of the Barcode image, the height of the bars, add borders, padding and more. Please consult the documentation for a complete range of formats and options supported by the =BARCODE() function in Google Forms.