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

現在表示しているURLを取得する機能を追加したらハマった件

Posted at

前回の拡張機能にボタンクリックでURLを追加できるように改造しようとして、copilotに聞いたり、検索したものの結局できなかったので、他のサイトを探して回ってようやく完成。
気づかずに3時間以上もかかってしまいました。気づいていれば30分程度で出来た気はするんですが…。

結論としては、 拡張機能の読み直しは拡張機能画面の再読み込み を押すこと。
サイドパネルを開閉したり、オン/オフでやっていたので、どうもちゃんと読み込めていなかったようです。
散々undefindが出続けて居たのが、再読み込みマークをクリックしたらあっさり通ったので、多分それが原因じゃないかと。

同じようにハマった人がいれば、その人の一助になればと記しておきます。


URL取得のための参考にさせていただいたのは以下の記事です。


ソースは以下に記載しておきます。マニフェストの権限設定が忘れそうで怖いですね。
CSSとservice-worker.jsには変更ありません。

manifest.json
{
    "manifest_version": 3,
    "name": "URLリストサイドパネル",
    "version": "1.1",
    "description": "URLリストを管理するサイドパネル",
    "permissions": ["sidePanel", "activeTab", "tabs"],
    "background": {
        "service_worker": "service-worker.js"
    },
    "action": {
        "default_title": "URLリストサイドパネル\nクリックするとサイドパネルが開きます"
    },
    "side_panel": {
        "default_path": "index.html"
    },
    "content_security_policy": {
        "extension_pages": "script-src 'self'; object-src 'self'"
    }
}
service-worker.js
chrome.runtime.onInstalled.addListener(() => {
    chrome.sidePanel.setPanelBehavior({ openPanelOnActionClick: true });
});
script.js
const dropzone = document.getElementById('dropzone');
const urllist = document.getElementById('urllist');
const copyButton = document.getElementById('copyButton');
const clearButton = document.getElementById('clearButton');
const getButton = document.getElementById('getButton');

dropzone.addEventListener('dragover', (event) => {
    event.preventDefault();
    dropzone.style.borderColor = '#aaa';
});

dropzone.addEventListener('dragleave', () => {
    dropzone.style.borderColor = '#ccc';
});

dropzone.addEventListener('drop', (event) => {
    event.preventDefault();
    dropzone.style.borderColor = '#ccc';

    const items = event.dataTransfer.items;
    for (let i = 0; i < items.length; i++) {
        if (items[i].kind === 'string' && items[i].type.match('^text/uri-list')) {
            items[i].getAsString((url) => {
                const li = document.createElement('li');
                li.textContent = url;
                urllist.appendChild(li);
            });
        }
    }
});

copyButton.addEventListener('click', () => {
    const urls = [];
    const listItems = urllist.getElementsByTagName('li');
    for (let i = 0; i < listItems.length; i++) {
        urls.push(listItems[i].textContent);
    }
    const urlText = urls.join('\n');
    navigator.clipboard.writeText(urlText).then(() => {
        alert('URLリストがクリップボードにコピーされました!');
    }).catch((err) => {
        alert('コピーに失敗しました: ' + err);
    });
});

clearButton.addEventListener('click', () => {
    urllist.innerHTML = '';
});

getButton.addEventListener('click',() =>{
    chrome.tabs.query({
        active: true,
        currentWindow: true,
    }, tabs => {
        const tab = tabs[0];
//        alert(tab.url);
        const li = document.createElement('li');
        li.textContent = tab.url;
        urllist.appendChild(li);

    });
})
style.css
#dropzone {
    width: 100%;
    height: 200px;
    border: 2px dashed #ccc;
    display: flex;
    align-items: center;
    justify-content: center;
    text-align: center;
}
ul {
    list-style-type: none;
    padding: 0;
}
#copyButton,#clearButton,#getButton {
    margin-top: 20px;
    padding: 10px 20px;
    border: none;
    background-color: #4CAF50;
    color: white;
    cursor: pointer;
}
index.html
<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <title>URLリスト作成</title>
    <link rel="stylesheet" href="styles.css"></head>
<body>
    <div id="dropzone">ここにURLをドラッグ&ドロップ</div>
    <ul id="urllist"></ul>
    <button id="getButton">現在表示しているページのURL取得</button>
    <button id="copyButton">クリップボードにコピー</button>
    <button id="clearButton">リストをクリア</button>
    <script src="script.js"></script>
</body>
</html>
1
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
1
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?