【问题标题】:Chrome Extension: How to inject code code into a new windowChrome 扩展程序:如何将代码代码注入新窗口
【发布时间】:2021-08-01 23:27:00
【问题描述】:

假设我想注入一些代码来在 chrome 中的新窗口上创建一个按钮(窗口本身是通过扩展的 popup.js 打开的)。我该怎么做呢?

【问题讨论】:

  • 欢迎来到 SO。当涉及到asking a good question 和这个question checklist 时,您可能会发现阅读网站help section 很有用。您为解决问题而编写的代码应包含minimal reproducible example,并包含在您的问题中。
  • 取决于 URL。如果它是扩展程序中的 html 文件,那么您不需要注入任何东西 - 只需在该 html 中加载脚本,如 <script src="file.js"></script。如果它是一个 Web URL,则向您的后台脚本发送一条消息,该脚本将打开选项卡,等待它加载,然后注入代码 example

标签: javascript google-chrome google-chrome-extension


【解决方案1】:

您可以使用诸如 documnet.body.appendChild() 之类的函数来代替 foreground.js 中的 console.log() 在打开具有我给出的名称的文件并以这种方式填充它们之后。您可以通过这种方式将任何您想要的内容添加到页面中。

background.js

function as(a,b,c) {
       
     chrome.tabs.executeScript(null, {file: "foreground.js"});
        chrome.tabs.insertCSS(null,{file:'./style.css'})
        console.log(a,b,c+'asd')
}
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
    as(tabId, changeInfo, tab);
}); 

foreground.js

window.onload=()=>{
    console.log('ok')
}

manifest.json

{
    "name": "plugin",
    "version": "1.0",
    "manifest_version":2,
    "background": {
        "scripts":["./background.js"]
    },
    "browser_action":{
        "default_popup":"popup.html"
    },
    "permissions":[
      "tabs",
        "https://*/*"
    ]
}

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    
</body>
</html>

style.css

button{
    color:red;
}

【讨论】:

    猜你喜欢
    • 2017-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-17
    相关资源
    最近更新 更多