Chrome 扩展提供了一套强大的 API,用于处理浏览器历史记录操作。通过 chrome.history API,开发者可以高效地实现搜索、管理和清理历史记录的功能。本文档详细介绍了该模块的功能,适合初学者及希望深入了解浏览器扩展开发的用户。
在 manifest.json
文件中声明 history
权限。例如:
{
"name": "My Extension",
"permissions": [
"history"
]
}
声明了该权限后,扩展程序可以正常访问浏览器中的历史记录功能。
搜索符合指定条件的历史记录。通过关键词或时间范围进行过滤,返回满足条件的记录。
该方法可用于开发浏览器插件,帮助用户快速搜索并整理浏览器的访问记录,例如查找过去一周访问过的某些特定网站。
chrome.history.search(
{
text: string, // Search keywords
startTime: number, // Start time (timestamp)
endTime: number, // End time (timestamp)
maxResults: number // Maximum number of results
},
function(results) { // Callback function
console.log(results);
}
);
搜索过去 7 天访问过的包含 "example" 的历史记录:
chrome.history.search(
{
text: 'example',
startTime: Date.now() - 7 * 24 * 60 * 60 * 1000, // Seven days ago
maxResults: 10
},
function(results) {
results.forEach(entry => console.log(entry.url));
}
);
返回包含历史记录对象的数组:
{
id: string, // Unique identifier
url: string, // Link address
title: string, // Page title
lastVisitTime: number, // Last visit timestamp
visitCount: number, // Visit count
typedCount: number // Manually typed count
}
startTime
和 endTime
的时间戳单位为毫秒。获取指定 URL 的访问详情,返回用户访问页面的方式及时间。
可用于分析用户访问特定网页的行为模式,例如通过点击链接还是手动输入访问。
chrome.history.getVisits(
{ url: string },
function(visitItems) {
console.log(visitItems);
}
);
获取指定 URL 的访问详情:
chrome.history.getVisits(
{ url: 'https://example.com' },
function(visitItems) {
visitItems.forEach(visit => console.log(visit.visitTime));
}
);
返回包含访问详情对象的数组:
{
visitId: string, // Unique identifier
visitTime: number, // Visit timestamp
referringVisitId: string, // Previous visit ID
transition: string // Transition type (e.g., link, typed)
}
transition
提供了用户访问来源的信息,可用于行为分析。向历史记录中添加新链接,模拟用户访问过某页面的行为。
在开发调试历史记录相关功能时,可使用该方法快速填充测试数据。
chrome.history.addUrl(
{ url: string },
function() {
console.log('URL added');
}
);
向历史记录中添加一个新链接:
chrome.history.addUrl(
{ url: 'https://example.com' },
function() {
console.log('URL successfully added!');
}
);
从历史记录中删除指定的链接。
开发清理工具时,帮助用户移除敏感或多余的历史记录。
chrome.history.deleteUrl(
{ url: string },
function() {
console.log('URL deleted');
}
);
从历史记录中删除一个链接:
chrome.history.deleteUrl(
{ url: 'https://example.com' },
function() {
console.log('Deleted from history!');
}
);
根据时间范围删除历史记录。
帮助用户快速清理指定时间段内的浏览记录,例如清理过去一周的隐私数据。
chrome.history.deleteRange(
{
startTime: number, // Start time
endTime: number // End time
},
function() {
console.log('History range deleted');
}
);
删除过去 7 天的所有历史记录:
chrome.history.deleteRange(
{
startTime: Date.now() - 7 * 24 * 60 * 60 * 1000, // Seven days ago
endTime: Date.now()
},
function() {
console.log('Deleted history for the last 7 days');
}
);
清空所有历史记录。
适用于开发一键清理工具,帮助用户快速清空浏览器的所有历史记录,释放存储空间。
无。
清空所有历史记录:
chrome.history.deleteAll(function() {
console.log('All history deleted');
});
本文详细说明了 chrome.history
提供的所有 API,包括搜索、获取详情、添加和删除操作。通过这些功能,开发者可以高效地管理用户的历史记录,构建更加智能的浏览器插件。下一篇文章将探讨 Chrome 扩展的其他模块及其应用场景,敬请期待。