5
1

タイトルの通りですが、chromeの拡張機能を作りました。
chromeの基本機能では、ブラウザ左下に小さくリンク先が表示されます。
視線を移すのが面倒&文字が小さくて視認性が悪い
という不満があったので、GIFのようなものを作りました。
(公開するのに若干時間がかかるので、公開出来次第、ストアのリンク追記します)

Animation2.gif

実装

  • manifest.json
  • popup.html
  • popup.html
  • contents.js
  • styles.css

を作成します。

manifest.json
{
  "manifest_version": 3,
  "name": "Big Link View",
  "version": "1.0",
  "description": "Displays the URL of a link when hovering over it.",
  "action": {
    "default_popup": "popup.html"
  },
  "content_scripts": [
    {
      "matches": ["<all_urls>"],
      "js": ["contents.js"],
      "css": ["styles.css"]
    }
  ]
}

popup.html
<!DOCTYPE html>
<html>
  <head>
    <title>Popup</title>
    <style>
      body {
        min-width: 200px;
        min-height: 100px;
      }
    </style>
  </head>
  <body>
    <h1>Big Link View</h1>
    <button id="close-button">close</button>
    <script src="popup.js"></script>
  </body>
</html>

popup.js
document.getElementById("close-button").addEventListener("click", () => {
  window.close();
});

contents.js
let hoverTimer;
let currentLink;
let mouseX;
let mouseY;

// マウスの位置を取得
document.addEventListener("mousemove", function (event) {
  mouseX = event.clientX;
  mouseY = event.clientY;
});

// 要素にマウスオーバー
document.addEventListener("mouseover", function (event) {
  // マウスオーバーした要素(親含め)にaタグが含まれる
  const target = event.target.closest("a");
  if (target && target.hasAttribute("href")) {
    currentLink = target;

    // 0.8秒後にリンクを表示
    hoverTimer = setTimeout(() => {
      const urlDisplay = document.createElement("div");
      urlDisplay.id = "url-display";
      urlDisplay.innerText = target.getAttribute("href");
      document.body.appendChild(urlDisplay);

      urlDisplay.style.left = `${mouseX}px`;
      urlDisplay.style.top = `${mouseY}px`;
      urlDisplay.style.transform = "translateY(-100%)";
    }, 800);
  }
});

// マウスアウト
document.addEventListener("mouseout", function (event) {
  if (currentLink) {
    clearTimeout(hoverTimer);
    const urlDisplay = document.getElementById("url-display");
    if (urlDisplay) {
      urlDisplay.remove();
    }
    currentLink = null;
  }
});

.styles.css
#url-display {
  position: absolute;
  background-color: yellow;
  color: black;
  border: 1px solid black;
  padding: 5px;
  z-index: 1000;
  font-size: 18px;
  font-weight: bold;
  pointer-events: none;
}

popupは、上部のタブからクリックしたときに表示されるもの。
contents.jsは拡張機能の本丸です。

今後

今後、改修したいのは以下3点

  1. 現在は0.8秒同じ要素をマウスオーバー(選択)した際に大きなリンクが表示されるように作りましたが、各自の設定で表示するまでの時間を変更できるようにしたい
  2. 表示されるリンクのスタイルを各自の設定から変更できるようにしたい
  3. クリックイベントで作られる遷移先も表示できるようにしたい(ただの願望。できるかどうかは調査必要)
5
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
5
1