首页 > 解决方案 > 从 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'),但它也不起作用。哪种方式是正确的?

标签: google-chromedomtext

解决方案


您不能从后台脚本访问 DOM。您只能从内容脚本访问 DOM。所以尝试放置以下代码:

var name = document.getElementsByClassName('auth_username').value; 警报(名称);

在 contentscript 中,它可以工作。


推荐阅读