4
1

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拡張でクリップボードにテキストをコピーする(Manifest V3)

Last updated at Posted at 2024-02-03

クリップボードにテキストをコピーする navigator.clipboard.writeText ですが、サービスワーカーでは Window.navigator が利用できません。しかし、タブにスクリプトを送り、実行させることで利用できます。

  • サービスワーカーで chrome.scripting APIを利用します
  • アクティブタブでスクリプトを実行させるため activeTab 権限が必要です
manigeft.json
{
  "name": "タイトルとURLをコピー",
  "description": "ページのタイトルとURLを Ctrl+Shift+X でMarkdown形式にてコピーします。",
  "version": "1.0",
  "manifest_version": 3,
  "background": {
    "service_worker": "service-worker.js"
  },
  "commands": {
    "copy-title-and-url": {
      "suggested_key": {
        "default": "Ctrl+Shift+X",
        "mac": "Command+Shift+X"
      },
      "description": "Copy title and URL"
    }
  },
  "permissions": [
    "activeTab",
    "scripting"
  ]
}
service-worker.js
chrome.commands.onCommand.addListener((command) => {
  chrome.tabs.query({ 'active': true, 'lastFocusedWindow': true }, tabs => {
    chrome.scripting.executeScript({
      target: { tabId: tabs[0].id },
      function: () =>
        navigator.clipboard.writeText(`[${document.title}](${location.href})`)
    });
  });
});

HTML形式でコピーする場合

service-worker.js
chrome.commands.onCommand.addListener((command) => {
  chrome.tabs.query({ 'active': true, 'lastFocusedWindow': true }, tabs => {
    chrome.scripting.executeScript({
      target: { tabId: tabs[0].id },
      function: () =>
        navigator.clipboard.write([
          new ClipboardItem({
            'text/html': new Blob(
              [`<a href="${location.href}">${document.title}</a>`],
              { type: 'text/html' }
            ),
            'text/plain': new Blob(
              [document.title],
              { type: 'text/plain' }
            )
          })]
        )
    });
  });
});

4
1
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
4
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?