4

を使用してドメイン名を取得しようとalert(document.domain);しましたが、サイトでテストしたときに正しいドメインを取得できませんでした。

「hiecjmnbaldlmopbbkifcelmaaalcfib」という奇妙な出力が得られます。

これもマニフェストに追加しました

  "content_scripts": [
        {
        "js": ["inject.js"]

        }
  ],

アラート (document.domain); inject.js 内の唯一のテキスト行です。

そして、これ<script type="text/javascript" src="inject.js"> </script>を後でメインのhtmlファイルに組み込みましたpopup.js

正しいドメイン URL を取得できない理由について何か考えはありますか?

ありがとう!

4

1 に答える 1

7

ポップアップ、バックグラウンド、またはオプション ページにいる場合、ページのドメインを取得するための間接的な方法があります。

以下のコードを参考にしてください。

デモンストレーション

マニフェスト.json

登録されたコンテンツ スクリプト、バックグラウンドおよびポップアップ スクリプトとマニフェスト ファイル、および関連する権限

{
    "name": "Domain Name",
    "description": "http://stackoverflow.com/questions/14796722/javascript-google-chrome-extension-getting-domain-name",
    "version": "1",
    "manifest_version": 2,
    "content_scripts": [
        {
            "matches": [
                "<all_urls>"
            ],
            "js": [
                "myscript.js"
            ]
        }
    ],
    "browser_action": {
        "default_popup": "popup.html"
    },
    "background": {
        "scripts": [
            "background.js"
        ]
    },
    "permissions": [
        "tabs",
        "<all_urls>"
    ]
}

myscript.js

console.log(document.domain);// Outputs present active URL of tab

popup.html

popup.jsCSPを凌駕するために登録されました。

<html>

    <head>
        <script src="popup.js"></script>
    </head>

    <body></body>

</html>

popup.js

のイベント リスナーを追加しDOM Content Loaded、ユーザーがオンになっているタブの URL をアクティブにしました。

document.addEventListener("DOMContentLoaded", function () {
    console.log(document.domain);//It outputs id of extension to console
    chrome.tabs.query({ //This method output active URL 
        "active": true,
        "currentWindow": true,
        "status": "complete",
        "windowType": "normal"
    }, function (tabs) {
        for (tab in tabs) {
            console.log(tabs[tab].url);
        }
    });
});

background.js

console.log(document.domain); //It outputs id of extension to console
chrome.tabs.query({ //This method output active URL 
    "active": true,
    "currentWindow": true,
    "status": "complete",
    "windowType": "normal"
}, function (tabs) {
    for (tab in tabs) {
        console.log(tabs[tab].url);
    }
});

出力

見つけるだろう

fgbhocadghoeonlokakijhnlplgkolbg

console.log(document.domain) の出力として; すべての拡張ページと

http://somedomain.com/

出力用tabs.query()

ただし、Content スクリプトの出力は常に

http://somedomain.com/

参考文献

于 2013-02-12T05:40:29.910 に答える