简体   繁体   中英

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.

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:

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

Thank you for helping me in advance <3!

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 :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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