【问题标题】:Chrome Extension: How to inject code code into a new windowChrome 扩展程序:如何将代码代码注入新窗口
【发布时间】:2021-08-01 23:27:00
【问题描述】:
假设我想注入一些代码来在 chrome 中的新窗口上创建一个按钮(窗口本身是通过扩展的 popup.js 打开的)。我该怎么做呢?
【问题讨论】:
-
-
取决于 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