gpt4 book ai didi

javascript - Chrome 扩展 : pass variables from popup html

转载 作者:搜寻专家 更新时间:2023-11-01 04:23:47 25 4
gpt4 key购买 nike

我正在尝试为 chrome 做一个非常简单的扩展,但我坚持从弹出式 html 传递变量。

这是我目前的代码:


list :

{
"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"
}

背景.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;

}
}
);

我的脚本.js

function foo(){
document.getElementById('submit-button').click();
}

setInterval(function(){
foo()}, 20000)

foo();

弹出窗口

 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);

})

弹出窗口

<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>

到目前为止,当您单击每 20 秒运行一次的提交按钮时,我会运行 foo()。我想要实现的是在弹出的 html 中添加一个数字,然后在 myscript.js 中使用该数字来设置 setInterval 函数的时间。

下面是一个案例场景:

我打开页面,点击扩展按钮。有一个带有表单的弹出窗口。我投入了 30000,然后击中了 sumbit。这样,foo() 将每 30 秒运行一次。

最佳答案

不需要后台脚本。

popup.js中注入(inject)脚本并传递值:

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 将使用注入(inject)的 timeout 变量:

.............
setInterval(foo, timeout);
.............

关于javascript - Chrome 扩展 : pass variables from popup html,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33479029/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com