从Chrome扩展名中的popup.html文件在background.js文件中运行一个函数
Run a function in the background .js file from the popup .html file in a Chrome extension
我正在尝试编写一个Chrome扩展。您可以通过单击Chrome扩展图标在图标之间切换,popup.html会显示您将通过单击设置的图标的预览
<input type="image" src="icon.png" onclick="helloWorld()"></input>
函数helloWorld()
在background.js文件中定义(同一目录:
chrome.browserAction.setIcon({
path : "/iconcat.png"
});
function helloWorld() {
chrome.browserAction.setIcon({
path : "/icon.png"
});
}
(首先要做的是将其设置为猫图标)
我将icon.png
和iconcat.png
以及.html和.js文件都放在同一目录中。
如何通过单击图像按钮来运行.js文件中的helloWorld()
函数?
-
默认情况下,不会执行内联脚本。您应该提取
onclick
内联处理程序,并将其移动到像popup.js
这样的外部脚本中。 -
要从弹出页面调用后台页面中的函数,您可以查看chrome.runtime.getBackgroundPage或chrome.extension.getBackgroundPage。
示例代码看起来像:
manifest.json
{
"name": "Emoji",
"version": "1.0",
"manifest_version": 2,
"description": "Show an Emoji in Chrome!.",
"browser_action": {
"default_icon": "icon.png",
"default_popup": "picker.html"
},
"background": {
"scripts": ["background.js"]
}
}
picker.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<input id="inputId" type="image" src="icon.png"></input>
<script src="picker.js"></script>
</body>
</html>
picker.js
document.getElementById("inputId").addEventListener("click", function() {
chrome.runtime.getBackgroundPage(function(backgroundPage) {
backgroundPage.helloWorld();
});
}, false);
background.js
chrome.browserAction.setIcon({
path : "/iconcat.png"
});
function helloWorld() {
chrome.browserAction.setIcon({
path : "/icon.png"
});
}
相关文章:
- 从JavaScript文件运行Firebug Lite
- 从本地文件运行时,$.get()无法正常工作
- 在 chrome 或 Firefox 中的调试控制台对.js文件运行 JSLint
- 从 JavaScript 对本地 SQLite 文件运行查询
- 代码在shell中运行,但提供'可以't查找变量'从文件运行时出错
- Grunt:如何只对修改后的文件运行任务
- Twitter引导程序无法从本地文件运行
- 量角器-通过量角器上传文件/运行exe
- 使用批处理文件运行咕噜声构建
- 从另一个.js文件运行.js文件
- 使用 JSF 和.xhtml文件运行开放层
- 从 html 文件运行外部 JavaScript 函数
- 如何使用 shell 脚本文件运行我的节点脚本
- 如何从 html 文件运行/调用 javascript 文件中的 javascript 函数
- 从 php 文件运行 javascript
- 加载 JavaScript 文件运行时
- Rails:Javascript 从一个文件运行,但不能从另一个文件运行
- 如何从外部文件运行函数作为表单的操作
- 如何对JSON文件运行javascript JSON模式
- 如何通过外部js文件运行javascript图像幻灯片