Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to open a mailto: link from a Chrome Extension?

I have a URL shortening Chrome extension called Shrtr. Right now, it allows users to copy the shortened URL to clipboard, but in the next version, I've added the ability to email the shortened URL, using a mailto: link (i.e. mailto:?subject=<original page title>&body=<short URL>).

The problem is, you cannot just assign document.location.href = 'mailto...'; from an extension. The following 2 methods worked for me, but with both, I end up with an open blank tab in the browser:

Method 1: window.open

var wnd = window.open(emailUrl);
setTimeOut(function() {
    wnd.close();
}, 500);

Notice the need to wait before closing the window. This works (i.e. mail client new message dialog appears, pre-populated), but the new tab remains open.

Method 2: using chrome.tabs

chrome.tabs.create({ url: emailUrl }, function(tab) {
    setTimeOut(function() {
        chrome.tabs.remove(tab.id);
    }, 500);
});

Again, works - but tab remains open. Any ideas?

like image 853
Traveling Tech Guy Avatar asked Feb 15 '14 02:02

Traveling Tech Guy


2 Answers

var emailUrl = "mailto:[email protected]";

    chrome.tabs.update({
        url: emailUrl
    });
like image 142
Yiping Avatar answered Nov 13 '22 19:11

Yiping


I realize this is an old question, but I myself had the same issue, and I figured out how to solve the problem so I thought I would share.

The issue stems from the fact that (I believe) you are calling the below code from your extension popup page.

chrome.tabs.create({ url: emailUrl }, function(tab) {
    setTimeout(function() {
        chrome.tabs.remove(tab.id);
    }, 500);
});

The problem with this is that as soon as a new tab is created, the popup page dies and the callback code is never executed.

We can remedy this by moving that code into a function within the background page whose lifetime is not tied to the popup page:

function sendEmail() {
    var emailUrl = "mailto:[email protected]";
    chrome.tabs.create({ url: emailUrl }, function(tab) {
        setTimeout(function() {
            chrome.tabs.remove(tab.id);
        }, 500);
    });
}

and calling it via chrome.extension.getBackgroundPage().sendEmail() from your popup page.

Using the above method, the default email client will be opened, and the new tab will be automatically closed after 500 milliseconds.

like image 40
Gabe O'Leary Avatar answered Nov 13 '22 17:11

Gabe O'Leary