Master Chrome Extension APIs: History, Downloads, and Storage Management

This article provides a comprehensive guide to Chrome extension development, covering the History, Downloads, and Storage APIs with practical code examples, advanced usage tips, privacy considerations, and custom scripts for efficient data management.

FunTester
FunTester
FunTester
Master Chrome Extension APIs: History, Downloads, and Storage Management

Browser History

Basic Functions

Search history using chrome.history.search.

chrome.history.search({text:'', startTime: Date.now() - 7*24*60*60*1000}, (results) => {
    console.log(results);
});

Get visit details with chrome.history.getVisits.

chrome.history.getVisits({url:'https://example.com'}, (details) => {
    console.log(details);
});

Delete a single URL or clear all history.

chrome.history.deleteUrl({url:'https://example.com'}, () => {
    console.log('URL deleted');
});
chrome.history.deleteAll(() => {
    console.log('All history cleared');
});

Advanced Usage

Delete history within a time range.

chrome.history.deleteRange({
    startTime: Date.now() - 24*60*60*1000,
    endTime: Date.now()
}, () => {
    console.log('Recent day history deleted');
});

Monitor navigation via chrome.tabs.onUpdated (since chrome.history has no change events).

chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
    if (changeInfo.url) {
        console.log(`User visited new page: ${changeInfo.url}`);
    }
});

Filter records with high visit count.

chrome.history.search({text:'', startTime: Date.now() - 30*24*60*60*1000}, (results) => {
    const frequent = results.filter(item => item.visitCount > 5);
    console.log(frequent);
});

Download Management

Basic Functions

Search downloads with chrome.downloads.search.

chrome.downloads.search({query:'', startTime: Date.now() - 7*24*60*60*1000}, (results) => {
    console.log(results);
});

Pause or cancel a download.

chrome.downloads.pause(downloadId, () => {
    console.log('Download paused');
});
chrome.downloads.cancel(downloadId, () => {
    console.log('Download cancelled');
});

Erase old download records.

chrome.downloads.erase({startTime: Date.now() - 30*24*60*60*1000}, () => {
    console.log('30‑day old download records cleared');
});

Practical Example

Automatically categorize downloads by file extension.

chrome.downloads.search({}, (downloads) => {
    const categorized = downloads.reduce((acc, item) => {
        const ext = item.filename.split('.').pop();
        acc[ext] = acc[ext] || [];
        acc[ext].push(item);
        return acc;
    }, {});
    console.log('Categorized downloads:', categorized);
});

Storage Management

Core Functions

Local persistent storage with chrome.storage.local.

chrome.storage.local.set({key:'value'}, () => {
    console.log('Data stored locally');
});

Cross‑device synchronization with chrome.storage.sync.

chrome.storage.sync.set({key:'value'}, () => {
    console.log('Data synced to cloud');
});

Listen for storage changes.

chrome.storage.onChanged.addListener((changes, areaName) => {
    console.log('Storage changed:', changes, areaName);
});

Custom Helper Scripts

Utility functions that combine the above APIs for automated cleanup and policy‑driven management.

// Delete a specific page from history
function deleteHistory(page){
    chrome.browsingData.removeHistory({url: page.url}, () => {
        console.log('Deleted page:', page.url);
    });
    chrome.history.deleteUrl({url: page.url}, () => {
        console.log('Deleted URL:', page.url);
    });
}

// Remove completed download records
function deleteDownloads(){
    chrome.downloads.search({}, (downloads) => {
        downloads.forEach(d => {
            if (d.state === 'complete') {
                chrome.downloads.erase({id: d.id}, () => {
                    console.log('Removed download:', d.id);
                });
            }
        });
    });
}

// Clear history older than 5 days
function clearHistoryRecord(){
    const cutoff = Date.now() - 5*24*60*60*1000;
    chrome.history.deleteRange({startTime: 0, endTime: cutoff}, () => {
        console.log('Deleted history older than 5 days');
    });
}

// Delete recent records based on domain rules (example placeholder logic)
function clearRecentRecord(){
    const end = Date.now() - 10*60*1000; // 10 minutes ago
    chrome.history.search({text:'', startTime:0, endTime:end, maxResults:1200}, (data) => {
        const domainMap = {}, countMap = {};
        data.forEach(page => {
            const url = new URL(page.url);
            const domain = url.hostname;
            const parts = domain.split('.');
            const countUrl = parts.length > 2 ? parts.slice(-2).join('.') : domain;
            // Insert custom deletion rules here, e.g., shouldDeletePage(domain)
        });
        console.info('Domain map:', domainMap);
    });
}
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaScriptChrome ExtensionWeb developmentHistory APIStorage APIDownloads API
FunTester
Written by

FunTester

10k followers, 1k articles | completely useless

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.