Olá,经过几个小时的寻找解决方案后,我无法解决“问题”,所以我在这里寻求帮助。 我的目标是创建一个谷歌扩展,显示当前选项卡/页面上有多少图像,为此,我尝试使用 javascript:
var x = document.images.length;
document.getElementById("idhere").innerHTML = x
与 html:
<p id="idhere"></p>
它可以工作,但不是我想要的方式,因为它在扩展程序的弹出窗口中查找图像,而不是选项卡(背景?)页面。然后它返回 0,因为我的弹出窗口中没有图像,但如果我添加图像,它会返回 1...
我的问题是:如何获取扩展程序弹出窗口“后面”的页面上的图像数量?
最佳答案
完成@jess的回答:
首先在 manifest.json 中添加以下行:
"content_scripts": [{
"matches": ["https://anylinkhere.com/*"],
"css": ["optionalstyle.css"],
"js": ["contentscript.js"]
}],
然后在扩展程序的文件夹中创建 contentscript.js 文件:
window.onload = function() {
chrome.runtime.sendMessage(document.images.length);
}
- window.onload = function() {}
将在页面完全加载时运行(需要加载所有图像)
- chrome.runtime.sendMessage(document.images.length);
将消息发送到您的background.js,并包含页面上的图像数量。
然后,在 background.js 中添加:
chrome.runtime.onMessage.addListener(function(response, sender, sendResponse,) {
chrome.storage.sync.set({"x": (response)}, function() {
console.log('Set x as '+ (response));
});
});
- chrome.runtime.onMessage.addListener...
接收您的contentscript.js发送的消息
- chrome.storage.sync.set({"x": (response)},...
将响应(图像数量)值存储到x,然后popup.js就可以访问。
- console.log('将 x 设置为 '+(响应));
记录它(可选)
现在在您的popup.js中:
chrome.storage.sync.get('x', function(data) {
document.getElementById("anyidhere").innerHTML = data.x;
});
- chrome.storage.sync.get('x',...
从存储中获取X值
- document.getElementById("anyidhere").innerHTML = data.x;
将 X 的值添加到具有指定 id 的元素(来自 popup.html),例如:
<body>
<p id="anyidhere"></p>
</body>
嗯,这就是我学习了两天所学到的全部内容,有些信息可能不正确或解释得不好,但它是有效的。
这是将信息从网页发送到弹出窗口的方式
关于javascript - Chrome 扩展 : Getting the document. images.length 来自当前页面,而不是弹出窗口。 (Javascript),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52376172/