为Chrome编写一个简单的扩展程序,该扩展程序需要在弹出窗口中显示有关全局Window
中对象,名为Tradecluster
的对象的信息,并带有选项,例如(在页面加载后从控制台运行)< / p>
> window.Tradecluster {options: {…}}
{
"priority" : "3",
"action" : "show"
}
在我的扩展程序中,我只有几个文件
manifest.json
{
"manifest_version": 2,
"name": "Tradecluster widget test",
"description": "Tradecluster widget test",
"version": "0.0.1",
"icons": {"128": "images/logo.png"},
"browser_action": {
"default_icon": "images/icon.png",
"default_popup": "popup.html"
},
"permissions": ["tabs"],
"content_scripts" : [
{
"matches": ["<all_urls>"],
"js": ["content.js"],
"run_at": "document_end"
}
]
}
popup.js
function setDOMInfo(info) {
if (info.version) {
document.getElementById('sf-widget').textContent = 'Installed';
document.getElementById('sf-version').textContent = info.version;
} else {
document.getElementById('sf-widget').textContent = 'Not installed';
document.getElementById('sf-version-p').style.display = 'none';
}
}
window.addEventListener('DOMContentLoaded', function () {
chrome.tabs.query({
active: true,
currentWindow: true
}, function (tabs) {
chrome.tabs.sendMessage(
tabs[0].id,
{from: 'popup', subject: 'DOMInfo'},
setDOMInfo);
});
});
content.js
chrome.runtime.sendMessage({
from: 'content',
subject: 'showPageAction'
});
chrome.runtime.onMessage.addListener(function (msg, sender, response) {
if ((msg.from === 'popup') && (msg.subject === 'DOMInfo')) {
// Here I find some additional info about connected scripts and
// find my script and extract version.
let version = false;
Array.from(document.scripts).forEach(function(item) {
if ((item.src).includes('tradecluster.tech/widget')) {
version = (item.src).split('/')[4];
}
});
let info = {
version: version
objectOptions: // here I need window.Tradecluster.options
};
// Directly respond to popup
response(info);
}
});
与相连的身体
popup.html
...
<body>
<div class="card text-white bg-dark" style="min-width: 380px;">
<div class="card-header">
<img class="logo-icon" src="images/logo.png">
<span class="logo-header">Tradecluster widget tester<span class="version">(0.0.1)</span></span>
</div>
<div class="card-body">
<p class="card-text">Widget: <span style="font-weight: bold" id="sf-widget"></span></p>
<p class="card-text" id="sf-version-p">Version: <span style="font-weight: bold" id="sf-version"></span></p>
<p class="card-text">Options: <pre style="font-weight: bold" id="sf-options"></pre></p>
</div>
<hr>
</div>
</body>
...
当将console.log(window)
放入content.js
脚本中时,我在控制台中收到带有许多参数的对象(看起来像全局窗口,但它没有任何Tradecluster
对象)。
如何从内容脚本中获取对象及其参数并将其传递给弹出窗口?找到一些解决方案,但由于未知原因,它们不起作用...