history.addUrl()

向浏览器的历史记录中添加一次访问给定 URL 的记录。此次访问的时间将记录为调用时的时间,并且 TransitionType 将被记录为 "link"。

这是一个异步函数,返回一个 Promise

语法

js
let addingUrl = browser.history.addUrl(
  details         // object
)

参数

details

object. 包含要添加的 URL 的对象。

url

string. 要添加的 URL。

title 可选

string: 页面的标题。如果未提供此项,则标题将记录为 null

transition 可选

history.TransitionType. 描述了此次页面导航的方式。如果未提供此项,则将记录 "link" 作为过渡类型。

visitTime 可选

numberstringobject. 指示日期和时间的数值。它可以表示为:一个 Date 对象,一个 ISO 8601 日期字符串,或者自纪元以来的毫秒数。将访问时间设置为此值。如果未提供此项,则将记录当前时间。

返回值

一个 Promise,当项目添加成功后,将以无参数的形式 fulfilled。

示例

添加一次访问 "https://example.org/" 的记录,然后通过搜索历史记录中的最新项目并打印日志来验证新记录是否已保存。

js
function onGot(results) {
  if (results.length) {
    console.log(results[0].url);
    console.log(new Date(results[0].lastVisitTime));
  }
}

browser.history
  .addUrl({ url: "https://example.org/" })
  .then(() =>
    browser.history.search({
      text: "https://example.org/",
      startTime: 0,
      maxResults: 1,
    }),
  )
  .then(onGot);

添加一次访问 "https://example.org" 的记录,但将其 visitTime 设置为 24 小时前,并将 transition 设置为 "typed"。

js
const DAY = 24 * 60 * 60 * 1000;

function oneDayAgo() {
  return Date.now() - DAY;
}

function onGot(visits) {
  for (const visit of visits) {
    console.log(new Date(visit.visitTime));
    console.log(visit.transition);
  }
}

browser.history
  .addUrl({
    url: "https://example.org/",
    visitTime: oneDayAgo(),
    transition: "typed",
  })
  .then(() =>
    browser.history.getVisits({
      url: "https://example.org/",
    }),
  )
  .then(onGot);

浏览器兼容性

注意: 此 API 基于 Chromium 的 chrome.history API。本文档源自 Chromium 代码中的 history.json