0

コンテキストメニューに「短縮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
}
4

1 に答える 1

0

その目的のために事前にコンテキストメニューを作成するとき(たとえば、拡張機能がロードされるとき)、私が知る限り、それはどちらか/または. 選択したすべてのテキストに対して取得するか、まったく取得しないことを意味します。したがって、動的に追加および削除する必要があります。

次のことができます。

  1. コンテンツ スクリプトで、 にリスナーを追加しdocument.onmouseupます。
  2. 呼び出されると、現在選択されているテキストの内容を確認します。
  3. URL の正規表現に一致する場合は、バックグラウンド ページにコンテキスト メニューを追加し、そうでない場合はコンテキスト メニューを削除します。
  4. ステップ4はありません。

したがって、コンテンツ スクリプトでは、次のようなものを使用できます。

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 (/^\s*https?:\/\/[a-zA-Z0-9$-_.+!*'(),]+\s*$/.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'});
    }
};

また、バックグラウンド スクリプトで、メッセージをリッスンし、それに応じてコンテキスト メニューを作成および削除します。

chrome.runtime.onMessage.addListener(
    function(request, sender, sendResponse) {
        if (request.action === 'addContextMenu') {
            // code to add the context menu
            // You can access the URL in 'request.url'
        } else if (request.action === 'removeContextMenu') {
            // Remove the context menu
        }
    }
);

メッセージパッシングについては、こちらのページをご覧ください。

注意: コンテンツ スクリプトからメニューを作成できるかもしれませんが、私は試していません。

于 2013-08-16T05:01:34.360 に答える