google-chrome-extension - 如何在当前选项卡上运行 chrome 扩展内容脚本
问题描述
我有一个 chrome 扩展,它传递如下信息: 1. content.js 分析页面并将结果发送到 background.js 2. popup.js 从 background.js 查询结果并将其显示在 popup.html 中。
预期行为:用户每次点击弹出按钮时,都会看到当前标签页的分析数据。
当前行为:每次用户单击弹出按钮时,他都会看到它分析的第一个选项卡的分析数据。
我尝试使用 chrome.tabs.query,但我没有弄清楚。去这里的路是什么?
Content.js(将 DOM 发送到后台)
var fromDOM = new XMLSerializer().serializeToString(document);
console.log(fromDOM);
chrome.runtime.sendMessage({method:'setTitle',title:fromDOM});
Background.js(内容和弹出窗口之间的代理)
var title;
chrome.runtime.onMessage.addListener(function(message,sender,sendResponse){
if(message.method == 'setTitle')
title = message.title;
else if(message.method == 'getTitle')
sendResponse(title);
});
popup.js(显示 DOM)
chrome.runtime.sendMessage({method:'getTitle'}, function(response){
document.querySelector("p").textContent = response;
});
显现
{
"manifest_version": 2,
"name": "B",
"version": "0.1",
"options_page": "options.html",
"background" : {
"scripts": ["background.js"]
},
"permissions": [
"storage",
"tabs"
],
"browser_action": {
"default_icon": "icon.png",
"default_popup": "popup.html"
},
"content_scripts": [
{
"matches": [
"<all_urls>"
],
"js": ["content.js"],
"run_at": "document_end"
}
]
}
解决方案
推荐阅读
- powerbuilder - 使用powerbuilder以编程方式在excel文件中启用宏
- anaconda - 在 tmux 中拆分窗格时保持旧的 conda env 处于激活状态
- jquery - jquery检查取消选中表行,除了单击子输入
- powershell - 将 HTML 转换为 CSV
- powershell - 继续脚本,一旦搜索完成
- adobe-xd - 如何通过 API 缩放画板及其项目?
- css - 页脚在 ios 设备上重叠登录表单(Safari + Chrome)
- sql - 如何在sql数据库中使用相同的名称将不同的ID更新为相同的ID
- javascript - 如何使用 javascript 在每张卡片中选择 1 个复选框
- c# - 如何获取邮箱中的邮件数量?