👩‍💻

#129 Chromeの拡張機能でマウスカーソルを変更してみた

に公開

はじめに

今回はChrome拡張機能を使って、ページ上のマウスカーソルをカスタマイズしてみます。

手順

フォルダとファイルを用意し、中身を書き換える

フォルダを作成し、その配下に以下のファイルを格納します。

・manifest.json(拡張機能の設定)
・popup.html(ポップアップ画面のHTML)
・popup.js(ポップアップ機能のスクリプト)
・content.js(ページのマウスカーソルを変更するスクリプト)
・cursor1.png(マウスカーソルにしたい画像①)
・cursor2.png(マウスカーソルにしたい画像②)

manifest.json

まず拡張機能の設定を行います。

{
  "manifest_version": 3,
  "name": "Custom Mouse Cursor",
  "version": "1.1",
  "description": "マウスカーソルをカスタム画像に変更します。",
  "permissions": ["scripting"],
  "host_permissions": ["http://*/*", "https://*/*"],
  "action": {
    "default_title": "マウスカーソル変更",
    "default_popup": "popup.html"
  },
  "content_scripts": [
    {
      "matches": ["http://*/*", "https://*/*"],
      "js": ["content.js"]
    }
  ],
  "web_accessible_resources": [
    {
      "resources": ["cursor1.png", "cursor2.png"],
      "matches": ["<all_urls>"]
    }
  ]
}

popup.html

マウスカーソルを選択するためのポップアップを作成します。

html
<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="UTF-8">
  <title>マウスカーソル変更</title>
</head>
<body>
  <h3>マウスカーソルを選択してください</h3>
  <button data-cursor="cursor1.png">デザイン1</button>
  <button data-cursor="cursor2.png">デザイン2</button>
  <button data-cursor="default">デフォルトに戻す</button>
  <script src="popup.js"></script>
</body>
</html>

popup.js

ポップアップから選択されたマウスカーソルを適用します。

jsx
document.querySelectorAll("button").forEach((button) => {
  button.addEventListener("click", (e) => {
    const cursor = e.target.getAttribute("data-cursor");
    chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
      chrome.tabs.sendMessage(tabs[0].id, { cursor: cursor }, (response) => {
        if (chrome.runtime.lastError) {
          console.error("Error sending message:", chrome.runtime.lastError.message);
        }
      });
    });
  });
});

content.js

選択されたマウスカーソルを適応します。

jsx
let currentCursor = "";

chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  if (request.cursor) {
    let newCursorStyle = "";
    if (request.cursor === "default") {
      newCursorStyle = "";
    } else {
      const cursorUrl = chrome.runtime.getURL(request.cursor);
      newCursorStyle = `url(${cursorUrl}), auto`;
    }
    document.body.style.cursor = newCursorStyle;
  }
});

Chromeに拡張機能を読み込ませる

  1. Chromeの拡張機能管理画面( chrome://extensions/ )を開く
  2. 右上の「デベロッパーモード」をオンにする
  3. 左上の「パッケージ化されていない拡張機能を読み込む」をクリックし、用意したフォルダを選択する

実際の挙動

自分が用意した画像をマウスカーソルとして設定できました。
「デザイン2」を押下で cursor2.png のマウスカーソルになり、「デフォルトに戻す」を押下で普段使っているマウスカーソルに戻ります。

最後に

今回はマウスカーソルを変更するChromeの拡張機能を作成してみました。
あまり役に立つ場面はないかもしれませんが、良ければ気分転換に試してみてください。
ご覧いただきありがとうございました。

Discussion