サイドパネルを持つエクステンションを作成しようとしています。このサイドパネルには、ホストページの状態に基づいてアクションを実行するボタンがあります。クロムエクステンションから注入されたjsからグローバルjs変数にアクセス
私は、this exampleの後ろにサイドパネルを挿入し、ボタンをオンにすることができますリスナー。しかし、私はグローバルjs変数にアクセスすることができません。デベロッパーコンソールでは、ホストページのスコープ内で、私が従っている変数(variable-configの名前)を見ることができます。サイドパネルのコンテキスト(popup.html)に次のエラーが表示されるとき -
VM523:1 Uncaught ReferenceError:configが定義されていません。 popup.htmlも別のスレッドで実行されているようです。
ボタンのonClickハンドラのグローバル変数jsにアクセスするにはどうすればよいですか?
マイコード:
manifest.jsonを
{
"manifest_version": 2,
"name": "Hello World",
"description": "This extension to test html injection",
"version": "1.0",
"content_scripts": [{
"run_at": "document_end",
"matches": [
"https://*/*",
"http://*/*"
],
"js": ["content-script.js"]
}],
"browser_action": {
"default_icon": "icon.png"
},
"background": {
"scripts":["background.js"]
},
"permissions": [
"activeTab"
],
"web_accessible_resources": [
"popup.html",
"popup.js"
]
}
background.js
chrome.browserAction.onClicked.addListener(function(){
chrome.tabs.query({active: true, currentWindow: true}, function(tabs){
chrome.tabs.sendMessage(tabs[0].id,"toggle");
})
});
コンテンツ-script.js
chrome.runtime.onMessage.addListener(function(msg, sender){
if(msg == "toggle"){
toggle();
}
})
var iframe = document.createElement('iframe');
iframe.style.background = "green";
iframe.style.height = "100%";
iframe.style.width = "0px";
iframe.style.position = "fixed";
iframe.style.top = "0px";
iframe.style.right = "0px";
iframe.style.zIndex = "9000000000000000000";
iframe.frameBorder = "none";
iframe.src = chrome.extension.getURL("popup.html")
document.body.appendChild(iframe);
function toggle(){
if(iframe.style.width == "0px"){
iframe.style.width="400px";
}
else{
iframe.style.width="0px";
}
}
popup.html
<head>
<script src="popup.js"> </script>
</head>
<body>
<h1>Hello World</h1>
<button name="toggle" id="toggle" >on</button>
</body>
popup.js
document.addEventListener('DOMContentLoaded', function() {
document.getElementById("toggle").addEventListener("click", handler);
});
function handler() {
console.log("Hello");
console.log(config);
}
私はホストページにアクセスできません。ホストページはchrome.storage.localに保存しません – Leon
拡張JSはページJSと対話できません。彼らはドキュメントでそれを伝えます。 – Jerinaw
@wOxxOmリンクをありがとう。私はそれに遭遇しましたが、それによって混乱するものもありました。私が理解するのを助けてくれますか?私は、JS変数を抽出してメッセージを送るために別のスクリプトを注入する必要がありますか? – Leon