当前位置: 首页 > article >正文

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

// 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

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

 

总结:


http://www.kler.cn/news/342988.html

相关文章:

  • 【最新华为OD机试E卷-支持在线评测】补种未成活胡杨(100分)多语言题解-(Python/C/JavaScript/Java/Cpp)
  • kali在git外网的代理
  • 环境变量
  • 75.【C语言】文件操作(3)
  • 第 3 章:使用 Vue 脚手架
  • 【JVM】实战篇
  • 【寻找one piece的算法之路】滑动窗口
  • 【代码笔记】
  • SpringBoot3.3 优雅启停定时任务
  • Java对请求参数进行校验
  • 用Python编写一个Web爬虫:自动获取感兴趣的新闻
  • JavaWeb——Vue组件库Element(5/6):案例:组件实现(概述、Form表单、Table表格、Pagination 分页、效果展示、完整代码)
  • uni-app如何搭建项目(一步一步教程)
  • 云渲染农场可以用哪些CG软件!
  • 【安卓逆向之内存读写
  • C++ 基于SDL库的 Visual Studio 2022 环境配置
  • 在培训考试小程序页面弹出半屏的弹窗交互实践
  • 使用Spring Security+jwt+redis实现登录注册逻辑
  • 请解释一下数据库的分区和分片?请解释一下数据库的日志和日志的重要性?
  • 【Python】使用优先级队列管理任务顺序