Search code examples
javascriptgoogle-chromebrowsergoogle-chrome-extensionbrowser-history

How to delete a specific browser history item based on URL and time range


I'm trying to use chrome.history to delete some specific visits that my extension is automatically visiting in a background window.

I found that there are at least a couple ways to do this:

  1. chrome.history.deleteUrl(url): which requires a URL and deletes all occurrences of it.

  2. chrome.history.deleteRange(range): which requires a startTime and endTime and deletes all URLs in that range.

How can I combine the two to delete a browser history visit with a specific URL and time range?

Or is there another, perhaps better, way to approach this entirely. Such as proactively setting a listener to delete URLs while automatically surfing them with some combination of the above functions and chrome.history.onVisited.addListener.

Thanks!


Solution

  • Here's what I came up with that you can run in a background console to test. It sets a listener, opens up a new tab, and the listener checks for a url match, then deletes the new history item. Lastly, it does a history search to confirm the item was removed:

    var url = 'http://stackoverflow.com'
    
    // Get current window
    chrome.windows.getCurrent(function(win) { 
    
        // Add temporary listener for new history visits
        chrome.history.onVisited.addListener(function listener(historyItem) {
    
            // Check if new history item matches URL
            if (historyItem.url.indexOf(url) > -1) {
    
                console.log('Found matching new history item', historyItem)
                var visit_time = historyItem.lastVisitTime
    
                // Delete range 0.5ms before and after history item
                chrome.history.deleteRange({
                    startTime: visit_time - 0.5, 
                    endTime: visit_time + 0.5
                }, function() { 
                    console.log('Removed Visit', historyItem)
    
                    // Get history with URL and see if last item is listed
                    chrome.history.search(
                        {text:'stackoverflow'}, 
                        function(result) { 
                            console.log('Show History is deleted:', result) 
                        } )
    
                });
                chrome.history.onVisited.removeListener(listener)
            }
        });
    
        // Create new tab
        chrome.tabs.create({ 
            windowId: win.id,
            url: url,
            active: false
        }, function(tab) {
            console.log('Created tab')
        }) 
    });
    

    Using only visit_time as both the startTime and endTime didn't work for me. Seems highly unlikely that this would delete more than the new entry though.