我正在制作一个 Chrome 扩展程序,将“缩短 URL”按钮添加到上下文菜单中。这是我第一次做任何与代码相关的事情,但我做得很好。
目前,只要您突出显示文本(使用 selectionText),我的按钮就会出现。我想要它做的只是在文本是“文本”URL(即纯文本是 URL,但不是链接)时出现。
我知道这是可能的,因为谷歌做到了。如果您突出显示并右键单击文本,则会出现“在Google 中搜索”按钮,但如果您突出显示并右键单击纯文本 URL,则会出现“转到”按钮。
我怎样才能在我的扩展中做到这一点?
谢谢你。
编辑:
我已经尝试使用 Timothée Boucher 的建议让它在我的扩展中工作,但我一定做错了什么(请参阅下面的评论)。
这是我到目前为止所得到的:
背景.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
});
内容脚本.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'});
}
};
清单.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
}