我正在尝试为chrome做一个非常简单的扩展,但我坚持从弹出式html传递一个变量。
这是我到目前为止的代码:
清单:
{
"background": {
"scripts": [ "background.js" ]
},
"browser_action": {
"default_icon": "img/test.png",
"default_popup": "popup.html",
"default_title": "Auto Clicker"
},
"description": "Auto click",
"manifest_version": 2,
"name": "Auto Clicker",
"permissions": [ "activeTab" ],
"version": "0.0.1"
}
background.js
chrome.extension.onMessage.addListener(
function(request, sender, sendResponse) {
switch (request.directive) {
case "popup-click-1":
// execute the content script
chrome.tabs.executeScript(null, { // defaults to the current tab
file: "myscript.js", // script to inject into page and run in sandbox
allFrames: true // This injects script into iframes in the page and doesn't work before 4.0.266.0.
});
sendResponse({}); // sending back empty response to sender
break;
}
}
);
myscript.js
function foo(){
document.getElementById('submit-button').click();
}
setInterval(function(){
foo()}, 20000)
foo();
popup.js
function clickHandler(e) {
chrome.extension.sendMessage({directive: "popup-click-1"}, function(response) {
this.close(); // close the popup when the background finishes processing request
});
}
document.addEventListener('DOMContentLoaded', function () {
document.getElementById('submit').addEventListener('click', clickHandler);
})
popup.html
<html>
<head>
<title>test</title>
<script src="popup.js"></script>
</head>
<body>
test
<form>
<input id="1" type = "text">
</br>
</form>
<button id='submit'> etst </button>
</body>
</html>
到目前为止,当您单击提交按钮时,我会运行foo(),该按钮每20秒运行一次。 我想要实现的是在弹出的html中添加一个数字,然后在myscript.js中使用该数字来设置setInterval函数的时间。
所以这是一个案例场景:
我打开页面,点击了扩展按钮。有一个带有表单的弹出窗口。我把30000然后点击了总和。这样,foo()将每30秒运行一次。
答案 0 :(得分:3)
不需要后台脚本。
在popup.js
中注入脚本并传递值:
function clickHandler(e) {
chrome.tabs.executeScript({
code: "var timeout=" + document.getElementById('1').value,
allFrames: true
}, function(result) {
chrome.tabs.executeScript({file: "myscript.js", allFrames: true}, function(result) {
});
});
}
myscript.js
将使用注入的timeout
变量:
.............
setInterval(foo, timeout);
.............