首页 > 解决方案 > 如何为 chrome 扩展上的当前文档执行 .querySelector()?

问题描述

我正在尝试构建一些插件,我只使用 JS,因为它是网络的母神。我正在尝试获取当前 PAGE 的元素!不是特定类的扩展选项卡。

加载窗口时,如果出现任何具有提供的类的元素,则返回它们的来源。

背景.js

document.getElementById("test").onclick = function() {
    alert(document.querySelector('.xd'));
    function modifyDOM() {
        //You can play with your DOM here or check URL against your regex
        return document.querySelector('.xd');
    }

    //We have permission to access the activeTab, so we can call chrome.tabs.executeScript:
    chrome.tabs.executeScript({
        code: modifyDOM //argument here is a string but function.toString() returns function's code
    }, (results) => {
        //Here we have just the innerHTML and not DOM structure

    });

};

popup.html

<!DOCTYPE html>
<html>
  <head>
    <style>
    body {
   min-width:500px;
   height:250px;
   font-family: "Lucida Grande", Helvetica, Arial, sans-serif;
    padding:10px;
   }
   </style>

   <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
  </head>
  <body>
    <button class="btn btn-primary"> Get Current URL</button>
    <p>You are browsing URL -  <span id="url"></span></p>
    <p>Your Video SRC: <span id="vid-src"></span></p>

    <ul id="links"></ul>

    <button id="test">TEST</button>

    <script src="background.js"></script>
  </body>
</html>

清单.json

{
  "name": "New",
  "version": "1.0",
  "description": "...",
  "permissions": ["activeTab", "declarativeContent", "storage","contextMenus"],

  "background": {
    "persistent": false,
    "scripts": ["background.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
}

标签: javascriptgoogle-chrome-extension

解决方案


推荐阅读