Google Extension Popup Page Send Mail Button

Introduction

In the development of Google extensions, how to add a link to the popup page, click this link to trigger the function of sending mail.

Analysis

  1. In the extension's folder, create an HTML file called popup.html and add the desired links in it. For example, you can add a simple link element:
<!DOCTYPE html>
<html>
<head>
   <title>My Extension</title>
</head>
<body>
   <a href="#" id="sendEmail">Send Email</a>

   <!-- add other content here -->

   <script src="popup.js"></script>
</body>
</html>
  1. In the same folder, create a JavaScript file called popup.js, and write code in it to handle the click event of the link and the function of sending an email. You can use the chrome.tabs.create method to create a new tab that opens the default email link. For example:
document. addEventListener('DOMContentLoaded', function() {
   var sendEmailLink = document. getElementById('sendEmail');

   sendEmailLink. addEventListener('click', function() {
     var subject = encodeURIComponent('Feedback');
     var body = encodeURIComponent('Dear Developer,\n\nI find XXXX,\n\nBest Regards,\nXXX');
     var emailUrl = 'mailto:example@example.com?subject=' + subject + '&body=' + body;

     chrome.tabs.create({ url: emailUrl });
   });
});

In the example above, the subject and body variables contain the default text you want to add. Use the encodeURIComponent function to encode the text to ensure it is passed correctly in the URL.

Keep in mind that some clients may ignore or handle the subject and body parameters differently, depending on the user's email client and configuration. Therefore, there is no guarantee that the default text will be displayed correctly in all cases.

  1. In the extension's manifest file (manifest.json), make sure you have added popup.html as the default page for the browser action (browser_action). For example:
{
   "manifest_version": 2,
   "name": "My Extension",
   "version": "1.0",
   "browser_action": {
     "default_popup": "popup.html"
   },
   "permissions": [
     "tabs"
   ]
}
  1. In the Chrome browser, open the extension management page (chrome://extensions/). Make sure developer mode is enabled and load your extensions folder.

Now, when you click on the extension's icon, a page pops up with a "Send Email" link. When the link is clicked, a new tab will open and the default email client will be launched, autofilling the recipient as example@example.com. You can modify the URL of the link and the recipients in the email as needed.

Note that you need to make sure you add the required permission ("tabs" in the above example) in your manifest file to be able to create new tabs.

Reference

Comments