google-chrome - 无法将消息从弹出窗口发送到内容
问题描述
我想通过以下代码将来自 Popup.js 的消息发送到 Content 脚本:
popup.js
chrome.tabs.query({ active: true, currentWindow: true }, function(tabs) {
chrome.tabs.sendMessage(tabs[0].id, { xpath: xpath });
});
并通过以下代码在内容脚本中接收它:
内容.js
chrome.runtime.onMessage.addListener(gotMessage());
function gotMessage(request, sender, sendResponse) {
alert("Hello");
}
我的清单是:
清单.json
{
"manifest_version": 2,
"name": "Auto Clicker",
"description": "Set Time, Set Element to Click, Start!",
"version": "0.1",
"permissions": ["tabs", "<all_urls>"],
"browser_action": {
"default_icon": {
"16": "images/icon-16x16.png",
"24": "images/icon-24x24.png",
"32": "images/icon-32x32.png"
},
"content_scripts": [
{
"matches": [
"<all_urls>"
],
"js": ["content.js"]
}
],
"default_title": "Auto Clicker",
"default_popup": "popup.html"
},
"icons": {
"16": "images/icon-16x16.png",
"24": "images/icon-24x24.png",
"32": "images/icon-32x32.png",
"128": "images/icon-128x128.png"
}
}
为什么它不工作?消息不会发送到内容脚本。
解决方案
我的问题是这样解决的:
// Inject Trigger to the current active Web Page
function injectTheScript() {
let xpath = document.getElementById("xpath-input").value || "";
chrome.tabs.query({ active: true, currentWindow: true }, function(tabs) {
chrome.tabs.executeScript({
code: `
(function () {
let btn = new XPathEvaluator()
.createExpression("${xpath}")
.evaluate(document, XPathResult.FIRST_ORDERED_NODE_TYPE).singleNodeValue;
btn.click();
})();
`
});
});
}
推荐阅读
- java - 应用程序语言更改默认为原始语言
- azure - 如何轻松锁定对 Azure 资源的访问?
- flutter - TextFormField 内的文本未与中心对齐 - Flutter
- material-ui - Material UI Picker:在焦点上打开 KeyboardDatePicker
- typescript - 为什么在这种情况下不能从参数推断出通用值 N?
- java - 尝试将数组添加到哈希表,以便我可以查看元素是否在不同的数组中匹配
- python - 从 QDialog 关闭主窗口
- c# - 尝试在 EF Core 中获取 SQL 时抛出 InvalidCastException
- python - 在元组中搜索组合
- python - 为什么使用 tweepy 时只能得到 1 条推文?