Search code examples
google-chromegoogle-chrome-extensionevent-handlingdom-events

Prevent event listener from been execute in Google Chrome Extension


I want to build a Google Chrome extension to sync all my bookmarks across Chrome so I have attached an event listener to onCreated;

chrome.bookmarks.onCreated.addListener(function (id, bookmark) {
    console.log('Hey bookmark created ' + id);
});

The idea is that when the user creates a new bookmark this onCreated event listener sends a JSON object to a server via an AJAX request stating that a bookmark has been created.

If the server then returns a JSON object which indicates that the new bookmark should be created on the browser I don't need the onCreated event listener to be executed.

Basically, the idea is that the event listener should only be triggered if a bookmark has been manually created by the user and not programmatically.

For example, the event listener should not be executed when if a bookmark is created using the following command;

chrome.bookmarks.create({
   parentId: '648',
   title: 'Google Folder'
});

Solution

  • If I understood correctly, you want to be able to pause chrome.bookmarks.onCreated while you are creating bookmarks programmatically. There is no clean way of doing it afaik, as Chrome API doesn't provide a way of removing event listeners, only adding.

    I would try to make some global switch probably:

    var listenerEnabled = true;
    chrome.bookmarks.onCreated.addListener(function (id, bookmark) {
        if(listenerEnabled) {
            console.log('Hey bookmark created ' + id);
        }
    });
    
    function createBookmark() {
        listenerEnabled = false;
        chrome.bookmarks.create({parentId: '648',title: 'Google Folder'}, function() {
            //enable with delay in case listener fires late
            setTimeout(function() {
                listenerEnabled = true;
            }, 500);
        });
    }
    

    Another way would be marking bookmarks created programattically (by appending something to title for example), and then inside the listener you can detect them and remove this mark.