Google chrome extension Chrome扩展弹出窗口-从background.js函数设置DIV文本
谢谢你的阅读 我一直在background.js和popup.html之间传递信息 在本例中,我试图从popup.html调用background.js中的testRequest。我已经看了几十个如何做到这一点的例子,并编写了尽可能多的解决方案,但我没有成功……这是我尝试过的解决方案之一: Popup.html:Google chrome extension Chrome扩展弹出窗口-从background.js函数设置DIV文本,google-chrome-extension,Google Chrome Extension,谢谢你的阅读 我一直在background.js和popup.html之间传递信息 在本例中,我试图从popup.html调用background.js中的testRequest。我已经看了几十个如何做到这一点的例子,并编写了尽可能多的解决方案,但我没有成功……这是我尝试过的解决方案之一: Popup.html: <html lang="en"> <head> <meta charset="utf-8" /> <title><
<html lang="en">
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<script type="text/javascript" src="background.js">
$(document).ready(function () {
document.getElementById("test").textContent = chrome.extension.getBackgroundPage.testRequest();
});
</script>
<div id="test"></div>
</body>
</html>
非常感谢你的帮助
~Brian您可以使用简单的消息传递来完成此操作。例如: Popup.html
<html lang="en">
<head>
<meta charset="utf-8" />
<title></title>
<script src="jquery.min.js"></script>
<script src="popup.js"></script>
</head>
<body>
<div id="test"></div>
</body>
</html>
background.js
$(function() {
chrome.runtime.sendMessage({method:"testRequest"},function(reply){
$('#test').text(reply);
});
});
chrome.runtime.onMessage.addListener(function(message,sender,sendRepsonse){
if(message.method == "testRequest")
sendResponse(testRequest());
});
function testRequest(){
return "yay!";
}
popup.html
中不允许使用内联代码,因此我们将其全部移动到一个外部文件中,您已经在使用jQuery,所以不要害怕更多地使用它,如果您正在使用它,请不要忘记包含它。您可以使用简单的消息传递来实现这一点。例如:
Popup.html
<html lang="en">
<head>
<meta charset="utf-8" />
<title></title>
<script src="jquery.min.js"></script>
<script src="popup.js"></script>
</head>
<body>
<div id="test"></div>
</body>
</html>
background.js
$(function() {
chrome.runtime.sendMessage({method:"testRequest"},function(reply){
$('#test').text(reply);
});
});
chrome.runtime.onMessage.addListener(function(message,sender,sendRepsonse){
if(message.method == "testRequest")
sendResponse(testRequest());
});
function testRequest(){
return "yay!";
}
popup.html
中不允许使用内联代码,因此我们将其全部移动到一个外部文件中,您已经在使用jQuery,所以不要害怕更多地使用它,如果您正在使用它,请不要忘记将其包括在内。谢谢您!我会投票支持这个答案,但我没有必要的代表…:-(谢谢BeardFist!我会投票支持这个答案,但我没有必要的代表…)-(