我想通过以下代码将消息从Popup.js发送到内容脚本中:
chrome.tabs.query({ active: true, currentWindow: true }, function(tabs) {
chrome.tabs.sendMessage(tabs[0].id, { xpath: xpath });
});
并通过以下代码在内容脚本中接收它:
chrome.runtime.onMessage.addListener(gotMessage());
function gotMessage(request, sender, sendResponse) {
alert("Hello");
}
我的清单是:
{
"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"
}
}
为什么它不起作用?邮件不会发送到内容脚本。
答案 0 :(得分:0)
我的问题已通过以下方式解决:
// 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();
})();
`
});
});
}