javascript - Chrome 扩展 : Getting the document. images.length 来自当前页面,而不是弹出窗口。 (Javascript)

标签 javascript html google-chrome-extension

Olá,经过几个小时的寻找解决方案后,我无法解决“问题”,所以我在这里寻求帮助。 我的目标是创建一个谷歌扩展,显示当前选项卡/页面上有多少图像,为此,我尝试使用 javascript:

var x = document.images.length;
document.getElementById("idhere").innerHTML = x

与 html:

<p id="idhere"></p>

它可以工作,但不是我想要的方式,因为它在扩展程序的弹出窗口中查找图像,而不是选项卡(背景?)页面。然后它返回 0,因为我的弹出窗口中没有图像,但如果我添加图像,它会返回 1...

我的问题是:如何获取扩展程序弹出窗口“后面”的页面上的图像数量?

最佳答案

完成@jess的回答:

首先在 ma​​nifest.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/

相关文章:

html - 内网应用HTML5语义标记有什么用?

html - 当浏览器最小化时, 'li' 中的最后 'ul' 个元素正在关闭

javascript - onActivated 和 onHighlighted 之间的区别?

javascript - list 图标第 1 行不是,列 : 1, 意外标记

javascript - 在弹出窗口内从 iframe 向后台脚本发送消息

javascript - 阻止所有滚动,直到函数触发

javascript - 如何从 javascript 运行 python 脚本?

java - 这是什么文档格式?

javascript - 如何在 angularjs Controller 中进行 google place api 搜索

javascript - 如何为 HTML 中表格的 <th> 元素提供工具提示