在我的contentScript.js中,我试图从其DOM中获取此leetcode.com问题(https://leetcode.com/problems/maximum-score-words-formed-by-letters/)的标题,并将其作为消息发送给我的background.js,但仅返回null
background.js
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
console.log("request: ", request)
console.log("sender: ", sender.url)
});
contentScript.js
problemName = document.querySelector('div[data-cy="question-title"]');
chrome.runtime.sendMessage({problemName: problemName});
manifest.json
{
"name": "Random Background Color",
"version": "1.0",
"description": "building my first extension!",
"permissions": [
"declarativeContent",
"storage",
"activeTab",
"tabs",
"webNavigation",
"contextMenus",
"https://leetcode.com/"
],
"background": {
"scripts": ["background.js"],
"persistent": false
},
"content_scripts": [
{
"matches": ["https://leetcode.com/problems/*"],
"js": ["contentScript.js"]
}
],
"browser_action": {
"default_popup": "popup.html",
"default_icon": {
"16": "images/get_started16.png",
"32": "images/get_started32.png",
"48": "images/get_started48.png",
"128": "images/get_started128.png"
}
},
"icons": {
"16": "images/get_started16.png",
"32": "images/get_started32.png",
"48": "images/get_started48.png",
"128": "images/get_started128.png"
},
"manifest_version": 2
}
所以在我的chrome扩展控制台中,它看起来像这样
request: {problemName: null}
sender: https://leetcode.com/problems/maximum-score-words-formed-by-letters/
problemName为null,但是当我运行
document.querySelector('div[data-cy="question-title"]');
在https://leetcode.com/problems/maximum-score-words-formed-by-letters/上的控制台内部,它向我发送了正确的标题