【发布时间】:2014-08-31 01:25:41
【问题描述】:
好的,所以我正在通过扩展程序更改网站的配色方案,这是我第一次使用 content_scripts,所以是的,我是一个完整的新手,请随意对待我。
问题是 tabs.connect 它不起作用,我需要标签 ID 还是什么?这是我目前所拥有的:
manifest.json:
{
"manifest_version": 2,
"name": "ROBLOX Color Scheme",
"description": "Edit the color scheme of the roblox bar! Note: Not created by roblox.",
"version": "1.0",
"permissions": [
"<all_urls>",
"tabs"
],
"browser_action": {
"default_icon": "Icon.png",
"default_popup": "Popup.html"
},
"content_scripts": [
{
"matches": ["http://www.roblox.com/*"],
"js": ["ContentScript.js"]
}
]
}
Popup.html:
<!DOCTYPE html>
<html>
<head>
<p>Choose a color:</p>
<input type="color" id="Color" value="">
<button type="button" id="Button">Change Color!</button>
</head>
<body>
<script src="Script.js"></script>
</body>
</html>
Script.js:
function ChangeColor() {
var TabId;
chrome.tabs.query({currentWindow: true, active: true}, function(tabArray) {
TabId = tabArray[0];
});
var port = chrome.tabs.connect(TabId, {name: "ColorShare"});
port.postMessage({Color: document.getElementById("Color").value});
}
document.getElementById('Color').addEventListener("click", ChangeColor);
ContentScript.js:
var Color;
chrome.runtime.onConnect.addListener(function(port) {
if (port.name == "ColorShare") then {
port.onMessage.addListener(function(msg) {
Color = msg.Color;
});
}
});
document.getElementsByClassName("header-2014 clearfix")[0].style.backgroundColor = Color;
感谢所有帮助,感谢您抽出宝贵时间回答我的问题!
编辑:由于我自己和回答者的帮助,现在一些文件已经更改,现在这些文件没有产生错误,但没有任何变化,您可能提供的任何帮助都会很棒!以下是当前代码:
Script.js:
chrome.tabs.query({currentWindow: true, active: true}, function(tabArray) {
var TabId = tabArray[0].id;
var port = chrome.tabs.connect(TabId, {name: "ColorShare"});
function ChangeColor() {
port.postMessage({Color: document.getElementById("Color").value});
}
document.getElementById('Color').addEventListener("click", ChangeColor);
});
ContentScript.js:
chrome.runtime.onConnect.addListener(function(port) {
if (port.name == "ColorShare") {
port.onMessage.addListener(function(msg) {
document.querySelector("header-2014 clearfix").style.backgroundColor = msg.Color;
});
}
});
编辑:这个问题已经解决了。我不得不使用完全支持内容脚本的 chrome.storage.sync.set 和 chrome.storage.sync.get!我会尽快发布使用的脚本!
【问题讨论】:
-
chrome.tabs.query是异步的,因此它可能会尝试连接到null的选项卡。移动您的端口定义,查询中的postMessage和TabId将被定义。 -
您能否提供如何做到这一点作为答案?
-
您需要为此使用端口吗?内置的message passing 非常适合在后台页面(扩展程序的主要部分)和内容脚本之间进行通信。
-
@anders 这就是我正在使用的(见 long-lived)
-
@warspyking 够公平
标签: javascript google-chrome google-chrome-extension communication content-script