Delete a single URL from a chrome-extension popup-

2019-09-15 13:00发布

问题:

Background information

I am trying to make a functional chrome-extension popup-window that enables the user to add links (based on the open tab's URL) when he desires it, and deletes one link or delete all of the links in just one click. Down below are all of my files! I must say in advance that I am not very good (and not experienced) with using jQuery's library but if that's the only solution that I have, than I will use it in my code.

The problem

The buttons to delete all the links and the button to add one link does work perfectly without bugs. However, the button to which one link should be deleted doesn't work, I tried various ways including splicing. I am trying to remove the link from the DOM and from the chrome.storage.local, both actions do not work. In the following code you can see all of the files I have thus far. The code of when the 'X' button is pressed doesn't get executed (see these pictures): https://i.stack.imgur.com/gg1Dy.png and https://i.stack.imgur.com/4oGdI.png

The code

manifest.json:

gist.github.com/kobrajunior/78acda830c2d1c384333542422f1494d

popup.js:

functions to look at: addToDom and removeMe and the very first event listener when the DOM is fully loaded

gist.github.com/kobrajunior/4852f85ae18cfb9edbe542a820b8c107

For extra information (if needed), the popup.html:

gist.github.com/kobrajunior/1c26691734c19391c62dc336ed2e1791

Thank you in advance.

回答1:

For the following lines in popup.js, you want to restore (show all the items/buttons) and bind listeners, however don't forget addToDom is called inside the callback of chrome.storage.local.get, that means by the time you assign value to allButtons, they're not added to DOM, that causes allButtons.length === 0 and you didn't bind anything in fact.

Try to move the binding logic inside the callback of restore (You may encounter other issues however that's not covered in this quesions).

document.addEventListener('DOMContentLoaded', function () {
    restore();
    var allButtons = document.getElementsByClassName('buttons');
    function listenI(i) {
        allButtons[i].addEventListener('click', () => removeMe(i));
    }
    for (var i = 0; i < allButtons.length; i++) {
        listenI(i);
    }
});

function restore() {
    // get the tab link and title
    chrome.storage.local.get({ urlList: [], titleList: [] }, function (data) {
        urlList = data.urlList;
        titleList = data.titleList;

        // add the titles and url's to the DOM
        for (var i = 0, n = urlList.length; i < n; i++) {
            addToDom(urlList[i], titleList[i]);
        }
    });
}