javascript 在 popup.html(chrome 扩展)中单击后执行脚本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20764517/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Execute script after click in popup.html (chrome extension)
提问by Vlad Holubiev
I am trying to execute javascript on a page when I click on a button in popup.html
. I tried to use such a way:
当我单击popup.html
. 我尝试使用这样的方式:
In background.js:
在background.js 中:
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo){
if(changeInfo.status == "loading") {
insert(tabId);
}
});
function insert(tabId) {
chrome.tabs.get(tabId, function(tab) {
$('button').click(function() {
chrome.tabs.executeScript(tab.id, {file: 'js/alert.js'});
});
});
}
Alert.js consists only of one string: alert('works');
Alert.js 仅包含一个字符串: alert('works');
Alert is just an example. Real script should do some DOM manipulation with opened tab after user clicks on a button im popup.html.
警报只是一个例子。在用户单击按钮 im popup.html 后,真实脚本应该对打开的选项卡进行一些 DOM 操作。
回答by greatghoul
I wrote a demo for your need.
我写了一个演示以满足您的需要。
https://gist.github.com/greatghoul/8120275
https://gist.github.com/greatghoul/8120275
alert.js
警报.js
alert('hello ' + document.location.href);
background.js
背景.js
// empty file, but needed
icon.png
图标.png
manifest.json
清单文件.json
{
"manifest_version": 2,
"name": "Click to execute",
"description": "Execute script after click in popup.html (chrome extension) http://stackoverflow.com/questions/20764517/execute-script-after-click-in-popup-html-chrome-extension.",
"version": "1.0",
"icons": {
"48": "icon.png"
},
"permissions": [
"tabs", "<all_urls>"
],
"browser_action": {
"default_icon": "icon.png",
"default_popup": "popup.html"
},
"background": {
"scripts": ["background.js"],
"persistent": false
}
}
popup.html
弹出窗口.html
<!DOCTYPE html>
<html>
<body style="width: 300px">
Open <a href="http://stackoverflow.com" target="_blank">this page</a> and then
<button id="clickme">click me</button>
<script type="text/javascript" src="popup.js"></script>
</body>
</html>
popup.js
弹出窗口.js
// var app = chrome.runtime.getBackgroundPage();
function hello() {
chrome.tabs.executeScript({
file: 'alert.js'
});
}
document.getElementById('clickme').addEventListener('click', hello);
回答by Jean-Luc Barat
You can also use Messaging:
您还可以使用消息传递:
in popup.js
在 popup.js 中
document.getElementById("clicked-btn").addEventListener("click", function(e) {
chrome.runtime.sendMessage({'myPopupIsOpen': true});
});
in background.js
在 background.js 中
chrome.runtime.onMessage.addListener(function(message, sender) {
if(!message.myPopupIsOpen) return;
// Do your stuff
});
Not tested but should works, further informations about Messaging.
未经测试但应该有效,有关Messaging 的更多信息。