コンテキストメニューに「短縮URL」ボタンを追加するChrome拡張機能を作成中です。コードに関連することをしたのはこれが初めてですが、うまくやっています。
現時点では、(selectionText を使用して) テキストを強調表示するたびにボタンが表示されます。私がやりたいことは、テキストが「テキスト」URL (つまり、リンクではなく URL であるプレーンテキスト) である場合にのみ表示されることです。
Googleがそうしているので、これが可能であることを私は知っています。テキストを強調表示して右クリックすると、[ Google で検索] ボタンが表示されますが、プレーン テキストの URL を強調表示して右クリックすると、[移動] ボタンが表示されます。
拡張機能でこれを行うにはどうすればよいですか?
ありがとうございました。
編集:
Timothée Boucher のアドバイスを使用して拡張機能で動作させようとしましたが、何か間違ったことをしているに違いありません (以下のコメントを参照)。
ここに私がこれまでに持っているものがあります:
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'});
}
};
マニフェスト.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
}