2
0

More than 1 year has passed since last update.

選択範囲のテキストを取得していろいろするためのクローム拡張サンプル

Last updated at Posted at 2022-12-28

「~をgoogleで検索」の右クリックメニュー(コンテキストメニュー)を再現しました。汎用性があると思い、ソースコードを公開します。

memo4.jpg
※私の期待したユースケース

マニフェストがv2(2021年までのブログ記事に散見)だとコードが動かなくなってしまっており、いろいろサンプルコードが動かなくなってしまっており、バージョンアップも簡単ではないので、材料集めに苦労しました。
というわけで作ったものを公開しますので誰かの種になりますように。

ちなみに下記のサンプルもおすすめです。
https://github.com/GoogleChrome/chrome-extensions-samples

manifest.josn
{
    "manifest_version": 3,
    "name": "nantoka-Search",
    "description": "選択範囲にあるテキストを取得して、新しいタブを開いて検索したりします。",
    "version": "0.9",
  
    "background": {
      "service_worker": "background.js"
    },
  
    "permissions": [
      "activeTab",
      "contextMenus",
      "scripting",
      "tabs"
    ]
  }

background.js
const updateContextMenus = async () => {
  await chrome.contextMenus.removeAll();

  chrome.contextMenus.create({
   //コンテキストメニューに追加
      id: "nantoka-search",
      title: "???を検索",
      contexts: ["all"]
  });
};

chrome.runtime.onInstalled.addListener(updateContextMenus);
chrome.runtime.onStartup.addListener(updateContextMenus);
chrome.contextMenus.onClicked.addListener((info, tab) => {
  
  var str = info.selectionText;
  chrome.tabs.create({url: "https://kensakusuruyo→/?"+code });
  
});

※クローム拡張の仕様を理解しないまま、主にいろんなサイトからコピペしまくって30分ほどで作りました。変なところがあればご指摘ください。

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0