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 堆栈:

总结:

相关推荐
T0uken17 分钟前
【Python】UV:单脚本依赖管理
chrome·python·uv
_龙衣18 分钟前
将 swagger 接口导入 apifox 查看及调试
前端·javascript·css·vue.js·css3
进取星辰1 小时前
25、Tailwind:魔法速记术——React 19 样式新思路
前端·react.js·前端框架
x-cmd2 小时前
[250512] Node.js 24 发布:ClangCL 构建,升级 V8 引擎、集成 npm 11
前端·javascript·windows·npm·node.js
夏之小星星2 小时前
el-tree结合checkbox实现数据回显
前端·javascript·vue.js
crazyme_62 小时前
前端自学入门:HTML 基础详解与学习路线指引
前端·学习·html
撸猫7912 小时前
HttpSession 的运行原理
前端·后端·cookie·httpsession
亦世凡华、3 小时前
Rollup入门与进阶:为现代Web应用构建超小的打包文件
前端·经验分享·rollup·配置项目·前端分享
Bl_a_ck3 小时前
【React】Craco 简介
开发语言·前端·react.js·typescript·前端框架
augenstern4164 小时前
webpack重构优化
前端·webpack·重构