我在互联网上有第https://somepage页。这是Chrome代码的一部分代码:
..............
<div class="wr">
<div class="auth_username">tesеDom@mail.com</div>
<div class="auth_stars">
<i class="fa fa-star-o fa-fw">
...........................
我已经看到许多答案和示例,但是我的代码仍然无法正常工作。似乎我缺少了一些东西。我的清单:
{
"manifest_version": 2,
"name": "Bot_copy",
"version": "1.0",
"content_security_policy": "script-src 'self' 'unsafe-eval'; object-src 'self'",
"icons": {
"48": "48x48.png",
"128": "128x128.png"
},
"content_scripts": [{
"matches": [ "https://mypage.my" ],
"js": ["helloWorld.js"]
}],
"permissions": [
"activeTab",
"alarms",
"clipboardRead",
"clipboardWrite",
"bookmarks",
"contextMenus",
"contentSettings",
"downloads",
"history",
"nativeMessaging",
"browsingData",
"proxy",
"webRequest",
"webRequestBlocking",
"cookies",
"tabs",
"webNavigation",
"storage",
"tabCapture",
"notifications",
"http://*/",
"https://*/",
"<all_urls>",
"unlimitedStorage",
"debugger"
],
"browser_action": {
"default_title": "Open"
},
"background": {
"scripts": ["background.js"]
}
}
内容脚本
window.onload = function() {
sendMessage();
}
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
sendResponse({
response: "Message received"
});
});
//Send message to background page
function sendMessage() {
//Construct & send message
chrome.runtime.sendMessage({
whattodo:"get_authname"
}, function(response) {
});
}
背景
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
var name = document.getElementsByClassName('auth_username').value;
alert(name);
sendResponse({
response: "Message received"
});
}
);
我收到警报“未定义”。
不知道。真奇怪,没有我不理解对象文档的适当文档。
似乎我想念如何使用documentc对象。我也尝试了document.getElementsByTagName('auth_username'),但它也不起作用。哪种方法正确?
答案 0 :(得分:0)
您无法从后台脚本访问DOM。您只能从内容脚本访问DOM。因此请尝试放置以下代码:
var name = document.getElementsByClassName('auth_username')。value; 警报(名称);
在内容脚本中,并且有效。