Chromium 中chrome.history扩展接口c++实现

一、前端 chrome.history定义

使用 chrome.history API 与浏览器的已访问网页的记录进行交互。您可以在浏览器的历史记录中添加、移除和查询网址。如需使用您自己的版本替换历史记录页面,请参阅覆盖网页

更多参考:chrome.history | API | Chrome for Developers (google.cn)

示例

若要试用此 API,请安装 chrome-extension-samples 中的 history API 示例 存储库

二、history接口在c++定义

chrome\common\extensions\api\history.json

out\Debug\gen\chrome\common\extensions\api\history.cc

src\out\Debug\gen\chrome\common\extensions\api\history.h

cpp 复制代码
// Copyright 2012 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

[
  {
    "namespace": "history",
    "description": "Use the <code>chrome.history</code> API to interact with the browser's record of visited pages. You can add, remove, and query for URLs in the browser's history. To override the history page with your own version, see <a href='override'>Override Pages</a>.",
    "types": [
      {
        "id": "TransitionType",
        "type": "string",
        "enum": ["link", "typed", "auto_bookmark", "auto_subframe", "manual_subframe", "generated", "auto_toplevel", "form_submit", "reload", "keyword", "keyword_generated"],
        "description": "The <a href='#transition_types'>transition type</a> for this visit from its referrer."
      },
      {
        "id": "HistoryItem",
        "type": "object",
        "description": "An object encapsulating one result of a history query.",
        "properties": {
          "id": {"type": "string", "minimum": 0, "description": "The unique identifier for the item."},
          "url": {"type": "string", "optional": true, "description": "The URL navigated to by a user."},
          "title": {"type": "string", "optional": true, "description": "The title of the page when it was last loaded."},
          "lastVisitTime": {"type": "number", "optional": true, "description": "When this page was last loaded, represented in milliseconds since the epoch."},
          "visitCount": {"type": "integer", "optional": true, "description": "The number of times the user has navigated to this page."},
          "typedCount": {"type": "integer", "optional": true, "description": "The number of times the user has navigated to this page by typing in the address."}
        }
      },
      {
        "id": "VisitItem",
        "type": "object",
        "description": "An object encapsulating one visit to a URL.",
        "properties": {
          "id": {"type": "string", "minimum": 0, "description": "The unique identifier for the corresponding $(ref:history.HistoryItem)."},
          "visitId": {"type": "string", "description": "The unique identifier for this visit."},
          "visitTime": {"type": "number", "optional": true, "description": "When this visit occurred, represented in milliseconds since the epoch."},
          "referringVisitId": {"type": "string", "description": "The visit ID of the referrer."},
          "transition": {
            "$ref": "TransitionType",
            "description": "The <a href='#transition_types'>transition type</a> for this visit from its referrer."
          },
          "isLocal": { "type": "boolean", "description": "True if the visit originated on this device. False if it was synced from a different device." }
        }
      },
      {
        "id": "UrlDetails",
        "type": "object",
        "properties": {
          "url": {"type": "string", "description": "The URL for the operation. It must be in the format as returned from a call to history.search."}
        }
      }
    ],
    "functions": [
      {
        "name": "search",
        "type": "function",
        "description": "Searches the history for the last visit time of each page matching the query.",
        "parameters": [
          {
            "name": "query",
            "type": "object",
            "properties": {
              "text": {"type": "string", "description": "A free-text query to the history service.  Leave empty to retrieve all pages."},
              "startTime": {"type": "number", "optional": true, "description": "Limit results to those visited after this date, represented in milliseconds since the epoch. If not specified, this defaults to 24 hours in the past."},
              "endTime": {"type": "number", "optional": true, "description": "Limit results to those visited before this date, represented in milliseconds since the epoch."},
              "maxResults": {"type": "integer", "optional": true, "minimum": 0, "description": "The maximum number of results to retrieve.  Defaults to 100."}
            }
          }
        ],
        "returns_async": {
          "name": "callback",
          "parameters": [
            { "name": "results", "type": "array", "items": { "$ref": "HistoryItem"} }
          ]
        }
      },
      {
        "name": "getVisits",
        "type": "function",
        "description": "Retrieves information about visits to a URL.",
        "parameters": [
          {
            "name": "details",
            "$ref": "UrlDetails"
          }
        ],
        "returns_async": {
          "name": "callback",
          "parameters": [
            { "name": "results", "type": "array", "items": { "$ref": "VisitItem"} }
          ]
        }
      },
      {
        "name": "addUrl",
        "type": "function",
        "description": "Adds a URL to the history at the current time with a <a href='#transition_types'>transition type</a> of \"link\".",
        "parameters": [
          {
            "name": "details",
            "$ref": "UrlDetails"
          }
        ],
        "returns_async": {
          "name": "callback",
          "optional": true,
          "parameters": []
        }
      },
      {
        "name": "deleteUrl",
        "type": "function",
        "description": "Removes all occurrences of the given URL from the history.",
        "parameters": [
          {
            "name": "details",
            "$ref": "UrlDetails"
          }
        ],
        "returns_async": {
          "name": "callback",
          "optional": true,
          "parameters": []
        }
      },
      {
        "name": "deleteRange",
        "type": "function",
        "description": "Removes all items within the specified date range from the history.  Pages will not be removed from the history unless all visits fall within the range.",
        "parameters": [
          {
            "name": "range",
            "type": "object",
            "properties": {
              "startTime": { "type": "number", "description": "Items added to history after this date, represented in milliseconds since the epoch." },
              "endTime": { "type": "number", "description": "Items added to history before this date, represented in milliseconds since the epoch." }
            }
          }
        ],
        "returns_async": {
          "name": "callback",
          "parameters": []
        }
      },
      {
        "name": "deleteAll",
        "type": "function",
        "description": "Deletes all items from the history.",
        "parameters": [],
        "returns_async": {
          "name": "callback",
          "parameters": []
        }
      }
    ],
    "events": [
      {
        "name": "onVisited",
        "type": "function",
        "description": "Fired when a URL is visited, providing the HistoryItem data for that URL.  This event fires before the page has loaded.",
        "parameters": [
          { "name": "result", "$ref": "HistoryItem"}
        ]
      },
      {
        "name": "onVisitRemoved",
        "type": "function",
        "description": "Fired when one or more URLs are removed from the history service.  When all visits have been removed the URL is purged from history.",
        "parameters": [
          {
            "name": "removed",
            "type": "object",
            "properties": {
              "allHistory": { "type": "boolean", "description": "True if all history was removed.  If true, then urls will be empty." },
              "urls": { "type": "array", "items": { "type": "string" }, "optional": true}
            }
          }
        ]
      }
    ]
  }
]

三、history API接口定义文件:

chrome\browser\extensions\api\bookmarks\bookmarks_api.h

chrome\browser\extensions\api\bookmarks\bookmarks_api.cc

cpp 复制代码
// Copyright 2012 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifndef CHROME_BROWSER_EXTENSIONS_API_HISTORY_HISTORY_API_H_
#define CHROME_BROWSER_EXTENSIONS_API_HISTORY_HISTORY_API_H_

#include <string>
#include <vector>

#include "base/memory/raw_ptr.h"
#include "base/scoped_observation.h"
#include "base/task/cancelable_task_tracker.h"
#include "base/values.h"
#include "chrome/common/extensions/api/history.h"
#include "components/history/core/browser/history_service.h"
#include "components/history/core/browser/history_service_observer.h"
#include "extensions/browser/browser_context_keyed_api_factory.h"
#include "extensions/browser/event_router.h"
#include "extensions/browser/extension_function.h"

class Profile;

namespace extensions {

// Observes History service and routes the notifications as events to the
// extension system.
class HistoryEventRouter : public history::HistoryServiceObserver {
 public:
  HistoryEventRouter(Profile* profile,
                     history::HistoryService* history_service);

  HistoryEventRouter(const HistoryEventRouter&) = delete;
  HistoryEventRouter& operator=(const HistoryEventRouter&) = delete;

  ~HistoryEventRouter() override;

 private:
  // history::HistoryServiceObserver.
  void OnURLVisited(history::HistoryService* history_service,
                    const history::URLRow& url_row,
                    const history::VisitRow& new_visit) override;
  void OnURLsDeleted(history::HistoryService* history_service,
                     const history::DeletionInfo& deletion_info) override;

  void DispatchEvent(Profile* profile,
                     events::HistogramValue histogram_value,
                     const std::string& event_name,
                     base::Value::List event_args);

  raw_ptr<Profile> profile_;
  base::ScopedObservation<history::HistoryService,
                          history::HistoryServiceObserver>
      history_service_observation_{this};
};

class HistoryAPI : public BrowserContextKeyedAPI, public EventRouter::Observer {
 public:
  explicit HistoryAPI(content::BrowserContext* context);
  ~HistoryAPI() override;

  // KeyedService implementation.
  void Shutdown() override;

  // BrowserContextKeyedAPI implementation.
  static BrowserContextKeyedAPIFactory<HistoryAPI>* GetFactoryInstance();

  // EventRouter::Observer implementation.
  void OnListenerAdded(const EventListenerInfo& details) override;

 private:
  friend class BrowserContextKeyedAPIFactory<HistoryAPI>;

  raw_ptr<content::BrowserContext> browser_context_;

  // BrowserContextKeyedAPI implementation.
  static const char* service_name() {
    return "HistoryAPI";
  }
  static const bool kServiceIsNULLWhileTesting = true;

  // Created lazily upon OnListenerAdded.
  std::unique_ptr<HistoryEventRouter> history_event_router_;
};

template <>
void BrowserContextKeyedAPIFactory<HistoryAPI>::DeclareFactoryDependencies();

// Base class for history function APIs.
class HistoryFunction : public ExtensionFunction {
 protected:
  ~HistoryFunction() override {}

  bool ValidateUrl(const std::string& url_string,
                   GURL* url,
                   std::string* error);
  bool VerifyDeleteAllowed(std::string* error);
  base::Time GetTime(double ms_from_epoch);
  Profile* GetProfile() const;
};

// Base class for history funciton APIs which require async interaction with
// chrome services and the extension thread.
class HistoryFunctionWithCallback : public HistoryFunction {
 public:
  HistoryFunctionWithCallback();

 protected:
  ~HistoryFunctionWithCallback() override;

  // The task tracker for the HistoryService callbacks.
  base::CancelableTaskTracker task_tracker_;
};

class HistoryGetVisitsFunction : public HistoryFunctionWithCallback {
 public:
  DECLARE_EXTENSION_FUNCTION("history.getVisits", HISTORY_GETVISITS)

 protected:
  ~HistoryGetVisitsFunction() override {}

  // ExtensionFunction:
  ResponseAction Run() override;

  // Callback for the history function to provide results.
  void QueryComplete(history::QueryURLResult result);
};

class HistorySearchFunction : public HistoryFunctionWithCallback {
 public:
  DECLARE_EXTENSION_FUNCTION("history.search", HISTORY_SEARCH)

 protected:
  ~HistorySearchFunction() override {}

  // ExtensionFunction:
  ResponseAction Run() override;

  // Callback for the history function to provide results.
  void SearchComplete(history::QueryResults results);
};

class HistoryAddUrlFunction : public HistoryFunction {
 public:
  DECLARE_EXTENSION_FUNCTION("history.addUrl", HISTORY_ADDURL)

 protected:
  ~HistoryAddUrlFunction() override {}

  // ExtensionFunction:
  ResponseAction Run() override;
};

class HistoryDeleteAllFunction : public HistoryFunctionWithCallback {
 public:
  DECLARE_EXTENSION_FUNCTION("history.deleteAll", HISTORY_DELETEALL)

 protected:
  ~HistoryDeleteAllFunction() override {}

  // ExtensionFunction:
  ResponseAction Run() override;

  // Callback for the history service to acknowledge deletion.
  void DeleteComplete();
};


class HistoryDeleteUrlFunction : public HistoryFunction {
 public:
  DECLARE_EXTENSION_FUNCTION("history.deleteUrl", HISTORY_DELETEURL)

 protected:
  ~HistoryDeleteUrlFunction() override {}

  // ExtensionFunction:
  ResponseAction Run() override;
};

class HistoryDeleteRangeFunction : public HistoryFunctionWithCallback {
 public:
  DECLARE_EXTENSION_FUNCTION("history.deleteRange", HISTORY_DELETERANGE)

 protected:
  ~HistoryDeleteRangeFunction() override {}

  // ExtensionFunction:
  ResponseAction Run() override;

  // Callback for the history service to acknowledge deletion.
  void DeleteComplete();
};

}  // namespace extensions

#endif  // CHROME_BROWSER_EXTENSIONS_API_HISTORY_HISTORY_API_H_

四、看下扩展调用history.getVisits 堆栈:

总结:

相关推荐
星秋Eliot9 分钟前
Flutter的三棵树
前端·flutter
正义的大古10 分钟前
OpenLayers常用控件 -- 章节六:全屏控件教程
前端·javascript·html·openlayers
lypzcgf21 分钟前
Coze源码分析-资源库-删除插件-前端源码-核心组件实现
前端·typescript·前端框架·react·coze·coze插件·智能体平台
草梅友仁2 小时前
草梅 Auth 1.6.0 发布密码强度组件 Twilio 短信支持 | 2025 年第 36 周草梅周报
前端·开源·github
正义的大古2 小时前
OpenLayers常用控件 -- 章节七:测量工具控件教程
前端·javascript·vue.js·openlayers
Hashan3 小时前
深入理解:Webpack编译原理
前端·webpack
雲墨款哥3 小时前
一个前端开发者的救赎之路-JS基础回顾(五)-数组
前端·javascript·面试
朱程3 小时前
深入JS(一):手写 Promise
前端·javascript
Hierifer3 小时前
跨端技术:浅聊双线程原理和实现
前端
FreeBuf_4 小时前
加密货币武器化:恶意npm包利用以太坊智能合约实现隐蔽通信
前端·npm·智能合约