0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【便利Chrome拡張】選択したテキストとそのページのリンクを任意の形式でクリップボードに保存する拡張機能

Posted at

表題の通り、今回は選択したテキストとそのページのリンクを任意の形式でクリップボードに保存する拡張機能のコードを紹介します。

自分で使っていてとても便利なので、ぜひ使ってみてください。

公開済みの拡張機能

こちらは私が公開している拡張機能です。
ただし、形式が[選択テキスト](ページURL)に限定されてしまっています。
これ以外の形式でコピーしてみたい方は、以下に紹介するコードを元にローカルで拡張機能を読み込んで使ってみてください!

コード本文

// コンテキストメニューを作成
chrome.runtime.onInstalled.addListener(() => {
  chrome.contextMenus.create({
    id: "copyAsLinkText",
    title: "リンクテキストとしてコピー",
    contexts: ["selection"], // テキスト選択時のみ表示
  });
});

// 右クリックメニューのクリックイベント
chrome.contextMenus.onClicked.addListener((info, tab) => {
  if (info.menuItemId === "copyAsLinkText" && info.selectionText) {
    // 選択されたテキストとURLをコンテンツスクリプトに渡す
    chrome.scripting.executeScript({
      target: { tabId: tab.id },
      function: copyToClipboard,
      args: [info.selectionText, info.pageUrl],
    });
  }
});

// コンテンツスクリプトとして実行する関数
function copyToClipboard(selectedText, pageUrl) {
  const formattedText = `[${selectedText}](${pageUrl})`;

  // クリップボードに書き込む
  navigator.clipboard.writeText(formattedText).catch((err) => {
    console.error(
      "link-clipper: 何らかのエラーによりクリップボードにコピーできませんでした",
      err
    );
  });
}
const formattedText = `[${selectedText}](${pageUrl})`;

この部分でコピーした時の形式を指定しているので、コピーしたい形式に変更してください。

ローカルに作成した拡張機能の読み込み方は以下を参考にしてみてください。
https://note.com/cute_echium873/n/n997dcf40b3a1

0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?