简体   繁体   English

单击popup.html上的按钮时运行background.js文件的简单方法

[英]simple way to run background.js file when a button on popup.html is clicked

I have been trying to run a function in my background.js file when I click a button on my popup.html file, I have tried a bunch of examples online and so far none of them have worked for me. 当我单击我的popup.html文件上的按钮时,我一直试图在background.js文件中运行一个函数,我已经在线尝试了很多示例,但到目前为止,这些示例都没有为我工作。

Here is what Ive tried: 这是我尝试过的:

$(".start-btn").click(function() {

    var task = loadTaskFromStorage($("#select-task").val());

    var checkbox = $('input[type="checkbox"]');
    var autobuy = $(checkbox).prop('checked');
    var delay = $("#checkout-ms").val();
    var count = localStorage.getItem('count');


    chrome.storage.sync.set({'task': task.cells, 'count': count}, function() {

    });

    chrome.storage.sync.set({'autobuy': autobuy, 'delay': delay}, function() {
    });

    chrome.runtime.sendMessage({'run': true);

then in the background.js file tried to do this: 然后在background.js文件中尝试执行以下操作:

chrome.runtime.onMessage.addListener(function(message, sender) {
  if(!message.run) return;

  finder();
});

function finder() {
    //pulling json info and opening url loop
});

I want to chrome.storage.sync.get all my things that I saved in my popup.js file then run the function.. I have tried a bunch of solutions and so far none of them have worked for me... 我想chrome.storage.sync.get我保存在popup.js文件中的所有内容,然后运行该函数。.我尝试了很多解决方案,但到目前为止,这些解决方案都对我没有帮助。

Thank you for helping me in advance <3! 感谢您提前帮助我<3!

popup.js : popup.js

Accumulate the data then send it over to the background: 累积数据,然后将其发送到后台:

$(".start-btn").click(function() {

    var task = loadTaskFromStorage($("#select-task").val());

    var checkbox = $('input[type="checkbox"]');
    var autobuy = $(checkbox).prop('checked');
    var delay = $("#checkout-ms").val();
    var count = localStorage.getItem('count');

    chrome.runtime.sendMessage({ run: true, data: {
        task: task.cells,
        count,
        autobuy,
        delay
    } });
}

background.js : background.js

Retrieve the data sent over from the popup, store it and use it: 检索从弹出窗口发送过来的数据,进行存储并使用:

chrome.runtime.onMessage.addListener(function(message, sender) {
    if(!message.run) return;

    var data = message.data;
    chrome.storage.sync.set(data, function() { /* ... */ });
    console.log(data);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM