google-chrome - 从 DOM 对象获取文本。Chrome 扩展程序
问题描述
我在互联网上有页面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'),但它也不起作用。哪种方式是正确的?
解决方案
您不能从后台脚本访问 DOM。您只能从内容脚本访问 DOM。所以尝试放置以下代码:
var name = document.getElementsByClassName('auth_username').value; 警报(名称);
在 contentscript 中,它可以工作。
推荐阅读
- c++ - 宏 htonl 将内部逗号解释为参数分隔符
- php - 无法在邮递员中测试 PHP 方法
- apache-flink - 在 Flink 的聚合原语中具有等效于 HOP_START
- dart - 如何在 Dart 中使用 `combineReducers` 指定类型注释?
- python - 从 python pandas 数据框中删除一些元素
- c# - C#通过单击标题对DataGridView进行排序给出了错误的顺序
- handsontable - Handsontable - 自定义 HTML 标头渲染器 -
- node.js - 如何使用护照身份验证更新包含 jwt 的 cookie
- java - 春季启动:org.codehaus.jackson.map.exc.UnrecognizedPropertyException:WebSphere 中无法识别的字段“XX”
- c - 整个程序中 __TIME__ 的常量值