I'm in the middle of making a Chrome extension that adds a 'Shorten URL' button to the context menu. This is the first time I've ever done anything code related, but I'm doing ok.
At the moment I've got my button coming up whenever you highlight text (using selectionText). What I want it to do is only come up if the text is a 'text' URL (i.e. plain text that's a URL, but not a link).
I know this is possible, because Google do it. If you highlight and right-click on text a 'Search Google for' button comes up, but if you highlight and right-click a plain text URL a 'Go to' button comes up.
How can I do this in my extension?
Thank you.
Edit:
I've tried to get it working in my extension using Timothée Boucher's advice, but I must be doing something wrong (see my comment below).
Here's what I've got so far:
background.js
function shortenurl1(info) {
var searchstring = info.pageUrl;
chrome.tabs.create({
url: "http://is.gd/create.php?url=" + searchstring
})
}
chrome.contextMenus.create({
title: "Shorten URL (with is.gd)",
contexts: ["page"],
onclick: shortenurl1
});
chrome.runtime.onMessage.addListener(
function (request, sender, sendResponse) {
if (request.action === 'addContextMenu') {
function shortenurl2(info) {
var searchstring = info.selectionText;
chrome.tabs.create({
url: "http://is.gd/create.php?url=" + searchstring
})
}
chrome.contextMenus.create({
title: "Shorten URL (with is.gd)",
contexts: ["selection"],
onclick: shortenurl2
})
} else if (request.action === 'removeContextMenu') {
chrome.contextMenus.remove({
title: "Shorten URL (with is.gd)"
})
}
}
);
function shortenurl3(info) {
var searchstring = info.linkUrl;
chrome.tabs.create({
url: "http://is.gd/create.php?url=" + searchstring
})
}
chrome.contextMenus.create({
title: "Shorten URL (with is.gd)",
contexts: ["link"],
onclick: shortenurl3
});
contentscript.js
document.onmouseup = function() {
var selectedText = window.getSelection().toString();
// this regex should work for very basic cases but doesn't follow the
// RFC strictly for what constitutes a URL. Full regex left as exercise ;-)
if (/((([A-Za-z]{3,9}:(?:\/\/)?)(?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+|(?:www.|[- ;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?: [\w]*))?)/.test(selectedText)) {
// send a message to the background page to add the context menu
chrome.extension.sendMessage({action: 'addContextMenu', url: selectedText});
} else {
// send a message to the background page to remove the context menu
chrome.extension.sendMessage({action: 'removeContextMenu'});
}
};
manifest.json
{
"background": {
"scripts": ["background.js"]
},
"content_scripts": [{
"run_at": "document_idle",
"js": ["contentscript.js"],
"matches": ["<all_urls>"]
}],
"description": "Shortens URLs using is.gd.",
"icons": {
"16": "icon16.png",
"48": "icon48.png"
},
"name": "is.gd context menu",
"permissions": ["contextMenus", "tabs", "clipboardWrite"],
"version": "1.0",
"manifest_version": 2
}