Chrome 扩展:将元素附加到弹出窗口而不是浏览器窗口

问题描述 投票:0回答:1

第一张图:当前状态,第二张图:目标状态

这是我的js代码(script.js):

在 popup.html 以及清单文件中,我包含 script.js

// ... created frameUp, frameDown, frameRight, frameLeft using createElement("DIV")

function addBorder(){
    document.body.appendChild(frameUp);
    document.body.appendChild(frameDown);
    document.body.appendChild(frameRight);
    document.body.appendChild(frameLeft);
}

document.addEventListener("DOMContentLoaded", function () {
    var button = document.createElement("button");
    button.innerHTML = 'click me';
    document.body.appendChild(button);
    button.onclick = addBorder;
    
});

此外,我发现当我将代码放在 addEventListener 中时,其中的每个 html 编辑都会应用于弹出窗口而不是整个浏览器。这就是为什么我在 addEventListener 中创建了按钮元素而不是边框元素。但是,我想在浏览器中绘制边框,而不是每次按下按钮时弹出窗口。

如何更改appendChild的位置,特别是从弹出窗口到浏览器窗口?当我使用 document.body 时,它到底指的是什么?

TLDR:想要弹出窗口中的按钮,但浏览器中的边框。不知道怎么办。

javascript html google-chrome-extension browser popup
1个回答
0
投票

声明权限:

确保扩展程序的manifest.json 文件声明了访问网页所需的权限。您可以添加这样的内容:

{
"name": "My Extension",
"version": "1.0",
"manifest_version": 2,
"permissions": ["activeTab", "storage", "webNavigation"],
"browser_action": {
  "default_popup": "popup.html"
},
"content_scripts": [
  {
    "matches": ["<all_urls>"],
    "js": ["content.js"]
  }
]
}

弹出 HTML (popup.html):

创建按钮并添加popup.js以将消息发送到content.js

<!DOCTYPE html>
<html>
 <head>
  <title>My Extension</title>
 </head>
 <body>
  <button id="editButton">Edit document.body</button>
  <script src="popup.js"></script>
  </body>
</html>

弹出 JavaScript (popup.js):

向弹出脚本添加逻辑,以便在单击按钮时向内容脚本发送消息。

document.getElementById('editButton').addEventListener('click', function() {
 chrome.tabs.query({ active: true, currentWindow: true }, function(tabs) 
 {
  chrome.tabs.sendMessage(tabs[0].id, { action: 'editBody' });
 });
});

处理内容脚本中的消息:

在内容脚本 (content.js) 中,您必须处理消息并执行必要的操作。

chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
 if (request.action === 'editBody') {
   // edit document.body
   document.body.style.backgroundColor = 'lightblue';
 }
});
© www.soinside.com 2019 - 2024. All rights reserved.