我已经为扩展编写了代码,但它不起作用:我无法在文档或扩展弹出窗口中 getElementById。我想当我点击弹出文本扩展名时开始游戏。
HTML 代码;
<!DOCTYPE html>
<html>
<head>
<style> p {color: purple;} </style>
</head>
<body>
<p id="pocinje"> Ekstenzija je pokrenuta i ceka se vrijeme za pocetak. </p>
<script src="background.js"> </script>
</body>
</html>
JAVASCRIPT;
document.getElementById("pocinje").onclick= function() {open};
function open() {
document.getElementById("startNewGame").click();
console.log("alorka");
}
我怎样才能解决这个问题?
最佳答案
扩展弹出窗口不能直接与“标签”内容(您的网页)交互。
只有“背景”和“内容”脚本可以与“标签”内容交互。 “弹出”脚本只能向他们发送消息,可以将另一个脚本插入其中(单击“选项卡”内容)。
1/您必须在“弹出”脚本和这些脚本之一之间建立通信
2/您的操作必须通过正确的扩展脚本插入到“选项卡”内容中
manifest.json:
首先,您必须在 list 中声明要与选项卡内容交互:
"permissions": ["tabs", "<all_urls>"],
其次,您必须声明一个“背景”文件,该文件将用作扩展程序的核心(仍在 list 中),至少要集中扩展程序脚本之间的通信:
"background": {
"scripts": ["background.js"]
},
第三,您必须声明您的“弹出窗口”(仍在 list 中):
"browser_action": {
"default_popup": "popup.html"
}
现在您已经设置了扩展,这是您可以使用的主要脚本:
popup.html:
弹出窗口插入将与“background.js”通信的“popup.js”文件:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="popup.js"></script>
</head>
<body>
<a id="popupBtn">Click me</a>
</body>
</html>
popup.js :
弹出脚本监听对弹出内容的单击,如果被触发,将向后台发送消息:
// always waits the document to be loaded when shown
document.addEventListener('DOMContentLoaded', function() {
// opens a communication between scripts
var port = chrome.runtime.connect();
// listens to the click of the button into the popup content
document.getElementById('popupBtn').addEventListener('click', function() {
// sends a message throw the communication port
port.postMessage({
'from': 'popup'
'start': 'Y'
});
});
});
背景.js :
后台脚本在弹出窗口和它自身之间创建一个通信,抛出“ chrome.runtime ”,如果消息正确,将在标签内容中插入一个代码:
// opens a communication port
chrome.runtime.onConnect.addListener(function(port) {
// listen for every message passing throw it
port.onMessage.addListener(function(o) {
// if the message comes from the popup
if (o.from && o.from === 'popup' && o.start && o.start === 'Y') {
// inserts a script into your tab content
chrome.tabs.executeScript(null, {
// the script will click the button into the tab content
code: "document.getElementById('pageBtn').click();"
});
}
});
});
更多信息在这里:https://developer.chrome.com/extensions/content_scripts#functionality
关于javascript - chrome 扩展中的 getElementById,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50660185/