Chromium 中chrome.cookies扩展接口c++实现分析

[复制链接]
发表于 2026-1-10 04:58:26 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

×
chrome.cookies

使用 chrome.cookies API 查询和修改 Cookie,并在 Cookie 发生更改时收到关照。
更多参考官网界说:chrome.cookies  |  API  |  Chrome for Developers (google.cn)
本文以加载一个整理cookies功能扩展为例 https://github.com/GoogleChrome/chrome-extensions-samples/tree/main/api-samples/cookies/cookie-clearer
 摘自官网扩展例子:
manifest.json
  1. {
  2.   "name": "Cookie Clearer",
  3.   "manifest_version": 3,
  4.   "version": "1.0",
  5.   "description": "Uses the chrome.cookies API by letting a user delete their cookies via a popup.",
  6.   "permissions": ["cookies"],
  7.   "host_permissions": ["<all_urls>"],
  8.   "action": {
  9.     "default_popup": "popup.html"
  10.   }
  11. }
复制代码
popup.js
  1. const form = document.getElementById('control-row');
  2. const input = document.getElementById('input');
  3. const message = document.getElementById('message');
  4. // The async IIFE is necessary because Chrome <89 does not support top level await.
  5. (async function initPopupWindow() {
  6.   let [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
  7.   if (tab?.url) {
  8.     try {
  9.       let url = new URL(tab.url);
  10.       input.value = url.hostname;
  11.     } catch {
  12.       // ignore
  13.     }
  14.   }
  15.   input.focus();
  16. })();
  17. form.addEventListener('submit', handleFormSubmit);
  18. async function handleFormSubmit(event) {
  19.   event.preventDefault();
  20.   clearMessage();
  21.   let url = stringToUrl(input.value);
  22.   if (!url) {
  23.     setMessage('Invalid URL');
  24.     return;
  25.   }
  26.   let message = await deleteDomainCookies(url.hostname);
  27.   setMessage(message);
  28. }
  29. function stringToUrl(input) {
  30.   // Start with treating the provided value as a URL
  31.   try {
  32.     return new URL(input);
  33.   } catch {
  34.     // ignore
  35.   }
  36.   // If that fails, try assuming the provided input is an HTTP host
  37.   try {
  38.     return new URL('http://' + input);
  39.   } catch {
  40.     // ignore
  41.   }
  42.   // If that fails ¯\_(ツ)_/¯
  43.   return null;
  44. }
  45. async function deleteDomainCookies(domain) {
  46.   let cookiesDeleted = 0;
  47.   try {
  48.     const cookies = await chrome.cookies.getAll({ domain });
  49.     if (cookies.length === 0) {
  50.       return 'No cookies found';
  51.     }
  52.     let pending = cookies.map(deleteCookie);
  53.     await Promise.all(pending);
  54.     cookiesDeleted = pending.length;
  55.   } catch (error) {
  56.     return `Unexpected error: ${error.message}`;
  57.   }
  58.   return `Deleted ${cookiesDeleted} cookie(s).`;
  59. }
  60. function deleteCookie(cookie) {
  61.   // Cookie deletion is largely modeled off of how deleting cookies works when using HTTP headers.
  62.   // Specific flags on the cookie object like `secure` or `hostOnly` are not exposed for deletion
  63.   // purposes. Instead, cookies are deleted by URL, name, and storeId. Unlike HTTP headers, though,
  64.   // we don't have to delete cookies by setting Max-Age=0; we have a method for that ;)
  65.   //
  66.   // To remove cookies set with a Secure attribute, we must provide the correct protocol in the
  67.   // details object's `url` property.
  68.   // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie#Secure
  69.   const protocol = cookie.secure ? 'https:' : 'http:';
  70.   // Note that the final URL may not be valid. The domain value for a standard cookie is prefixed
  71.   // with a period (invalid) while cookies that are set to `cookie.hostOnly == true` do not have
  72.   // this prefix (valid).
  73.   // https://developer.chrome.com/docs/extensions/reference/cookies/#type-Cookie
  74.   const cookieUrl = `${protocol}//${cookie.domain}${cookie.path}`;
  75.   return chrome.cookies.remove({
  76.     url: cookieUrl,
  77.     name: cookie.name,
  78.     storeId: cookie.storeId
  79.   });
  80. }
  81. function setMessage(str) {
  82.   message.textContent = str;
  83.   message.hidden = false;
  84. }
  85. function clearMessage() {
  86.   message.hidden = true;
  87.   message.textContent = '';
  88. }
复制代码
popup.html
  1. <!doctype html>
  2. <html>
  3.   <head>
  4.     <script src="popup.js" type="module"></script>
  5.   </head>
  6.   <body>
  7.     <form id="control-row">
  8.       <label for="input">Domain:</label>
  9.       <input type="text" id="input" />
  10.       <br />
  11.       <button id="go">Clear Cookies</button>
  12.     </form>
  13.     <span id="message" hidden></span>
  14.   </body>
  15. </html>
复制代码

一、看下c++提供 的cookies接口界说  chrome\common\extensions\api\cookies.json
  1. // Copyright 2012 The Chromium Authors
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. [
  5.   {
  6.     "namespace": "cookies",
  7.     "description": "Use the <code>chrome.cookies</code> API to query and modify cookies, and to be notified when they change.",
  8.     "types": [
  9.       {
  10.         "id": "SameSiteStatus",
  11.         "type": "string",
  12.         "enum": ["no_restriction", "lax", "strict", "unspecified"],
  13.         "description": "A cookie's 'SameSite' state (https://tools.ietf.org/html/draft-west-first-party-cookies). 'no_restriction' corresponds to a cookie set with 'SameSite=None', 'lax' to 'SameSite=Lax', and 'strict' to 'SameSite=Strict'. 'unspecified' corresponds to a cookie set without the SameSite attribute."
  14.       },
  15.       {
  16.         "id": "CookiePartitionKey",
  17.         "type": "object",
  18.         "description": "Represents a partitioned cookie's partition key.",
  19.         "properties": {
  20.           "topLevelSite": {"type": "string", "optional": true, "description": "The top-level site the partitioned cookie is available in."}
  21.         }
  22.       },
  23.       {
  24.         "id": "Cookie",
  25.         "type": "object",
  26.         "description": "Represents information about an HTTP cookie.",
  27.         "properties": {
  28.           "name": {"type": "string", "description": "The name of the cookie."},
  29.           "value": {"type": "string", "description": "The value of the cookie."},
  30.           "domain": {"type": "string", "description": "The domain of the cookie (e.g. "www.google.com", "example.com")."},
  31.           "hostOnly": {"type": "boolean", "description": "True if the cookie is a host-only cookie (i.e. a request's host must exactly match the domain of the cookie)."},
  32.           "path": {"type": "string", "description": "The path of the cookie."},
  33.           "secure": {"type": "boolean", "description": "True if the cookie is marked as Secure (i.e. its scope is limited to secure channels, typically HTTPS)."},
  34.           "httpOnly": {"type": "boolean", "description": "True if the cookie is marked as HttpOnly (i.e. the cookie is inaccessible to client-side scripts)."},
  35.           "sameSite": {"$ref": "SameSiteStatus", "description": "The cookie's same-site status (i.e. whether the cookie is sent with cross-site requests)."},
  36.           "session": {"type": "boolean", "description": "True if the cookie is a session cookie, as opposed to a persistent cookie with an expiration date."},
  37.           "expirationDate": {"type": "number", "optional": true, "description": "The expiration date of the cookie as the number of seconds since the UNIX epoch. Not provided for session cookies."},
  38.           "storeId": {"type": "string", "description": "The ID of the cookie store containing this cookie, as provided in getAllCookieStores()."},
  39.           "partitionKey": {"$ref": "CookiePartitionKey", "optional": true, "description": "The partition key for reading or modifying cookies with the Partitioned attribute."}
  40.         }
  41.       },
  42.       {
  43.         "id": "CookieStore",
  44.         "type": "object",
  45.         "description": "Represents a cookie store in the browser. An incognito mode window, for instance, uses a separate cookie store from a non-incognito window.",
  46.         "properties": {
  47.           "id": {"type": "string", "description": "The unique identifier for the cookie store."},
  48.           "tabIds": {"type": "array", "items": {"type": "integer"}, "description": "Identifiers of all the browser tabs that share this cookie store."}
  49.         }
  50.       },
  51.       {
  52.         "id": "OnChangedCause",
  53.         "type": "string",
  54.         "enum": ["evicted", "expired", "explicit", "expired_overwrite", "overwrite"],
  55.         "description": "The underlying reason behind the cookie's change. If a cookie was inserted, or removed via an explicit call to "chrome.cookies.remove", "cause" will be "explicit". If a cookie was automatically removed due to expiry, "cause" will be "expired". If a cookie was removed due to being overwritten with an already-expired expiration date, "cause" will be set to "expired_overwrite".  If a cookie was automatically removed due to garbage collection, "cause" will be "evicted".  If a cookie was automatically removed due to a "set" call that overwrote it, "cause" will be "overwrite". Plan your response accordingly."
  56.       },
  57.       {
  58.         "id": "CookieDetails",
  59.         "type": "object",
  60.         "description": "Details to identify the cookie.",
  61.         "properties": {
  62.           "url": {"type": "string", "description": "The URL with which the cookie to access is associated. This argument may be a full URL, in which case any data following the URL path (e.g. the query string) is simply ignored. If host permissions for this URL are not specified in the manifest file, the API call will fail."},
  63.           "name": {"type": "string", "description": "The name of the cookie to access."},
  64.           "storeId": {"type": "string", "optional": true, "description": "The ID of the cookie store in which to look for the cookie. By default, the current execution context's cookie store will be used."},
  65.           "partitionKey": {"$ref": "CookiePartitionKey", "optional": true, "description": "The partition key for reading or modifying cookies with the Partitioned attribute."}
  66.         }
  67.       }
  68.     ],
  69.     "functions": [
  70.       {
  71.         "name": "get",
  72.         "type": "function",
  73.         "description": "Retrieves information about a single cookie. If more than one cookie of the same name exists for the given URL, the one with the longest path will be returned. For cookies with the same path length, the cookie with the earliest creation time will be returned.",
  74.         "parameters": [
  75.           {
  76.             "name": "details",
  77.             "$ref": "CookieDetails"
  78.           }
  79.         ],
  80.         "returns_async": {
  81.           "name": "callback",
  82.           "parameters": [
  83.             {
  84.               "name": "cookie", "$ref": "Cookie", "optional": true, "description": "Contains details about the cookie. This parameter is null if no such cookie was found."
  85.             }
  86.           ]
  87.         }
  88.       },
  89.       {
  90.         "name": "getAll",
  91.         "type": "function",
  92.         "description": "Retrieves all cookies from a single cookie store that match the given information.  The cookies returned will be sorted, with those with the longest path first.  If multiple cookies have the same path length, those with the earliest creation time will be first. Only retrieves cookies for domains which the extension has host permissions to.",
  93.         "parameters": [
  94.           {
  95.             "type": "object",
  96.             "name": "details",
  97.             "description": "Information to filter the cookies being retrieved.",
  98.             "properties": {
  99.               "url": {"type": "string", "optional": true, "description": "Restricts the retrieved cookies to those that would match the given URL."},
  100.               "name": {"type": "string", "optional": true, "description": "Filters the cookies by name."},
  101.               "domain": {"type": "string", "optional": true, "description": "Restricts the retrieved cookies to those whose domains match or are subdomains of this one."},
  102.               "path": {"type": "string", "optional": true, "description": "Restricts the retrieved cookies to those whose path exactly matches this string."},
  103.               "secure": {"type": "boolean", "optional": true, "description": "Filters the cookies by their Secure property."},
  104.               "session": {"type": "boolean", "optional": true, "description": "Filters out session vs. persistent cookies."},
  105.               "storeId": {"type": "string", "optional": true, "description": "The cookie store to retrieve cookies from. If omitted, the current execution context's cookie store will be used."},
  106.               "partitionKey": {"$ref": "CookiePartitionKey", "optional": true, "description": "The partition key for reading or modifying cookies with the Partitioned attribute."}
  107.             }
  108.           }
  109.         ],
  110.         "returns_async": {
  111.           "name": "callback",
  112.           "parameters": [
  113.             {
  114.               "name": "cookies", "type": "array", "items": {"$ref": "Cookie"}, "description": "All the existing, unexpired cookies that match the given cookie info."
  115.             }
  116.           ]
  117.         }
  118.       },
  119.       {
  120.         "name": "set",
  121.         "type": "function",
  122.         "description": "Sets a cookie with the given cookie data; may overwrite equivalent cookies if they exist.",
  123.         "parameters": [
  124.           {
  125.             "type": "object",
  126.             "name": "details",
  127.             "description": "Details about the cookie being set.",
  128.             "properties": {
  129.               "url": {"type": "string", "description": "The request-URI to associate with the setting of the cookie. This value can affect the default domain and path values of the created cookie. If host permissions for this URL are not specified in the manifest file, the API call will fail."},
  130.               "name": {"type": "string", "optional": true, "description": "The name of the cookie. Empty by default if omitted."},
  131.               "value": {"type": "string", "optional": true, "description": "The value of the cookie. Empty by default if omitted."},
  132.               "domain": {"type": "string", "optional": true, "description": "The domain of the cookie. If omitted, the cookie becomes a host-only cookie."},
  133.               "path": {"type": "string", "optional": true, "description": "The path of the cookie. Defaults to the path portion of the url parameter."},
  134.               "secure": {"type": "boolean", "optional": true, "description": "Whether the cookie should be marked as Secure. Defaults to false."},
  135.               "httpOnly": {"type": "boolean", "optional": true, "description": "Whether the cookie should be marked as HttpOnly. Defaults to false."},
  136.               "sameSite": {"$ref": "SameSiteStatus", "optional": true, "description": "The cookie's same-site status. Defaults to "unspecified", i.e., if omitted, the cookie is set without specifying a SameSite attribute."},
  137.               "expirationDate": {"type": "number", "optional": true, "description": "The expiration date of the cookie as the number of seconds since the UNIX epoch. If omitted, the cookie becomes a session cookie."},
  138.               "storeId": {"type": "string", "optional": true, "description": "The ID of the cookie store in which to set the cookie. By default, the cookie is set in the current execution context's cookie store."},
  139.               "partitionKey": {"$ref": "CookiePartitionKey", "optional": true, "description": "The partition key for reading or modifying cookies with the Partitioned attribute."}
  140.             }
  141.           }
  142.         ],
  143.         "returns_async": {
  144.           "name": "callback",
  145.           "optional": true,
  146.           "min_version": "11.0.674.0",
  147.           "parameters": [
  148.             {
  149.               "name": "cookie", "$ref": "Cookie", "optional": true, "description": "Contains details about the cookie that's been set.  If setting failed for any reason, this will be "null", and $(ref:runtime.lastError) will be set."
  150.             }
  151.           ]
  152.         }
  153.       },
  154.       {
  155.         "name": "remove",
  156.         "type": "function",
  157.         "description": "Deletes a cookie by name.",
  158.         "parameters": [
  159.           {
  160.             "name": "details",
  161.             "$ref": "CookieDetails"
  162.           }
  163.         ],
  164.         "returns_async": {
  165.           "name": "callback",
  166.           "optional": true,
  167.           "min_version": "11.0.674.0",
  168.           "parameters": [
  169.             {
  170.               "name": "details",
  171.               "type": "object",
  172.               "description": "Contains details about the cookie that's been removed.  If removal failed for any reason, this will be "null", and $(ref:runtime.lastError) will be set.",
  173.               "optional": true,
  174.               "properties": {
  175.                 "url": {"type": "string", "description": "The URL associated with the cookie that's been removed."},
  176.                 "name": {"type": "string", "description": "The name of the cookie that's been removed."},
  177.                 "storeId": {"type": "string", "description": "The ID of the cookie store from which the cookie was removed."},
  178.                 "partitionKey": {"$ref": "CookiePartitionKey", "optional": true, "description": "The partition key for reading or modifying cookies with the Partitioned attribute."}
  179.               }
  180.             }
  181.           ]
  182.         }
  183.       },
  184.       {
  185.         "name": "getAllCookieStores",
  186.         "type": "function",
  187.         "description": "Lists all existing cookie stores.",
  188.         "parameters": [],
  189.         "returns_async": {
  190.           "name": "callback",
  191.           "parameters": [
  192.             {
  193.               "name": "cookieStores", "type": "array", "items": {"$ref": "CookieStore"}, "description": "All the existing cookie stores."
  194.             }
  195.           ]
  196.         }
  197.       }
  198.     ],
  199.     "events": [
  200.       {
  201.         "name": "onChanged",
  202.         "type": "function",
  203.         "description": "Fired when a cookie is set or removed. As a special case, note that updating a cookie's properties is implemented as a two step process: the cookie to be updated is first removed entirely, generating a notification with "cause" of "overwrite" .  Afterwards, a new cookie is written with the updated values, generating a second notification with "cause" "explicit".",
  204.         "parameters": [
  205.           {
  206.             "type": "object",
  207.             "name": "changeInfo",
  208.             "properties": {
  209.               "removed": {"type": "boolean", "description": "True if a cookie was removed."},
  210.               "cookie": {"$ref": "Cookie", "description": "Information about the cookie that was set or removed."},
  211.               "cause": {"min_version": "12.0.707.0", "$ref": "OnChangedCause", "description": "The underlying reason behind the cookie's change."}
  212.             }
  213.           }
  214.         ]
  215.       }
  216.     ]
  217.   }
  218. ]
复制代码
同时会天生
out\Debug\gen\chrome\common\extensions\api\cookies.h
out\Debug\gen\chrome\common\extensions\api\cookies.cc
此文件是cookies.json 界说的一个c++实现,主动天生请勿手动更改【tools\json_schema_compiler\compiler.py】。
二、cookies api接口界说:
       chrome\browser\extensions\api\cookies\cookies_api.h
       chrome\browser\extensions\api\cookies\cookies_api.cc
  1. // Copyright 2012 The Chromium Authors
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. // Defines the Chrome Extensions Cookies API functions for accessing internet
  5. // cookies, as specified in the extension API JSON.
  6. #ifndef CHROME_BROWSER_EXTENSIONS_API_COOKIES_COOKIES_API_H_
  7. #define CHROME_BROWSER_EXTENSIONS_API_COOKIES_COOKIES_API_H_
  8. #include <memory>
  9. #include <string>
  10. #include "base/memory/raw_ptr.h"
  11. #include "base/values.h"
  12. #include "chrome/browser/ui/browser_list_observer.h"
  13. #include "chrome/common/extensions/api/cookies.h"
  14. #include "extensions/browser/browser_context_keyed_api_factory.h"
  15. #include "extensions/browser/event_router.h"
  16. #include "extensions/browser/extension_function.h"
  17. #include "mojo/public/cpp/bindings/receiver.h"
  18. #include "mojo/public/cpp/bindings/remote.h"
  19. #include "net/cookies/canonical_cookie.h"
  20. #include "net/cookies/cookie_access_result.h"
  21. #include "net/cookies/cookie_change_dispatcher.h"
  22. #include "services/network/public/mojom/cookie_manager.mojom.h"
  23. #include "third_party/abseil-cpp/absl/types/optional.h"
  24. #include "url/gurl.h"
  25. class Profile;
  26. namespace extensions {
  27. // Observes CookieManager Mojo messages and routes them as events to the
  28. // extension system.
  29. class CookiesEventRouter : public BrowserListObserver {
  30. public:
  31.   explicit CookiesEventRouter(content::BrowserContext* context);
  32.   CookiesEventRouter(const CookiesEventRouter&) = delete;
  33.   CookiesEventRouter& operator=(const CookiesEventRouter&) = delete;
  34.   ~CookiesEventRouter() override;
  35.   // BrowserListObserver:
  36.   void OnBrowserAdded(Browser* browser) override;
  37. private:
  38.   // This helper class connects to the CookieMonster over Mojo, and relays Mojo
  39.   // messages to the owning CookiesEventRouter. This rather clumsy arrangement
  40.   // is necessary to differentiate which CookieMonster the Mojo message comes
  41.   // from (that associated with the incognito profile vs the original profile),
  42.   // since it's not possible to tell the source from inside OnCookieChange().
  43.   class CookieChangeListener : public network::mojom::CookieChangeListener {
  44.    public:
  45.     CookieChangeListener(CookiesEventRouter* router, bool otr);
  46.     CookieChangeListener(const CookieChangeListener&) = delete;
  47.     CookieChangeListener& operator=(const CookieChangeListener&) = delete;
  48.     ~CookieChangeListener() override;
  49.     // network::mojom::CookieChangeListener:
  50.     void OnCookieChange(const net::CookieChangeInfo& change) override;
  51.    private:
  52.     raw_ptr<CookiesEventRouter> router_;
  53.     bool otr_;
  54.   };
  55.   void MaybeStartListening();
  56.   void BindToCookieManager(
  57.       mojo::Receiver<network::mojom::CookieChangeListener>* receiver,
  58.       Profile* profile);
  59.   void OnConnectionError(
  60.       mojo::Receiver<network::mojom::CookieChangeListener>* receiver);
  61.   void OnCookieChange(bool otr, const net::CookieChangeInfo& change);
  62.   // This method dispatches events to the extension message service.
  63.   void DispatchEvent(content::BrowserContext* context,
  64.                      events::HistogramValue histogram_value,
  65.                      const std::string& event_name,
  66.                      base::Value::List event_args,
  67.                      const GURL& cookie_domain);
  68.   raw_ptr<Profile> profile_;
  69.   // To listen to cookie changes in both the original and the off the record
  70.   // profiles, we need a pair of bindings, as well as a pair of
  71.   // CookieChangeListener instances.
  72.   CookieChangeListener listener_{this, false};
  73.   mojo::Receiver<network::mojom::CookieChangeListener> receiver_{&listener_};
  74.   CookieChangeListener otr_listener_{this, true};
  75.   mojo::Receiver<network::mojom::CookieChangeListener> otr_receiver_{
  76.       &otr_listener_};
  77. };
  78. // Implements the cookies.get() extension function.
  79. class CookiesGetFunction : public ExtensionFunction {
  80. public:
  81.   DECLARE_EXTENSION_FUNCTION("cookies.get", COOKIES_GET)
  82.   CookiesGetFunction();
  83. protected:
  84.   ~CookiesGetFunction() override;
  85.   // ExtensionFunction:
  86.   ResponseAction Run() override;
  87. private:
  88.   void GetCookieListCallback(
  89.       const net::CookieAccessResultList& cookie_list,
  90.       const net::CookieAccessResultList& excluded_cookies);
  91.   // Notify the extension telemetry service when API is called.
  92.   void NotifyExtensionTelemetry();
  93.   GURL url_;
  94.   mojo::Remote<network::mojom::CookieManager> store_browser_cookie_manager_;
  95.   absl::optional<api::cookies::Get::Params> parsed_args_;
  96. };
  97. // Implements the cookies.getAll() extension function.
  98. class CookiesGetAllFunction : public ExtensionFunction {
  99. public:
  100.   DECLARE_EXTENSION_FUNCTION("cookies.getAll", COOKIES_GETALL)
  101.   CookiesGetAllFunction();
  102. protected:
  103.   ~CookiesGetAllFunction() override;
  104.   // ExtensionFunction:
  105.   ResponseAction Run() override;
  106. private:
  107.   // For the two different callback signatures for getting cookies for a URL vs
  108.   // getting all cookies. They do the same thing.
  109.   void GetAllCookiesCallback(const net::CookieList& cookie_list);
  110.   void GetCookieListCallback(
  111.       const net::CookieAccessResultList& cookie_list,
  112.       const net::CookieAccessResultList& excluded_cookies);
  113.   // Notify the extension telemetry service when API is called.
  114.   void NotifyExtensionTelemetry();
  115.   GURL url_;
  116.   mojo::Remote<network::mojom::CookieManager> store_browser_cookie_manager_;
  117.   absl::optional<api::cookies::GetAll::Params> parsed_args_;
  118. };
  119. // Implements the cookies.set() extension function.
  120. class CookiesSetFunction : public ExtensionFunction {
  121. public:
  122.   DECLARE_EXTENSION_FUNCTION("cookies.set", COOKIES_SET)
  123.   CookiesSetFunction();
  124. protected:
  125.   ~CookiesSetFunction() override;
  126.   ResponseAction Run() override;
  127. private:
  128.   void SetCanonicalCookieCallback(net::CookieAccessResult set_cookie_result);
  129.   void GetCookieListCallback(
  130.       const net::CookieAccessResultList& cookie_list,
  131.       const net::CookieAccessResultList& excluded_cookies);
  132.   enum { NO_RESPONSE, SET_COMPLETED, GET_COMPLETED } state_;
  133.   GURL url_;
  134.   bool success_;
  135.   mojo::Remote<network::mojom::CookieManager> store_browser_cookie_manager_;
  136.   absl::optional<api::cookies::Set::Params> parsed_args_;
  137. };
  138. // Implements the cookies.remove() extension function.
  139. class CookiesRemoveFunction : public ExtensionFunction {
  140. public:
  141.   DECLARE_EXTENSION_FUNCTION("cookies.remove", COOKIES_REMOVE)
  142.   CookiesRemoveFunction();
  143. protected:
  144.   ~CookiesRemoveFunction() override;
  145.   // ExtensionFunction:
  146.   ResponseAction Run() override;
  147. private:
  148.   void RemoveCookieCallback(uint32_t /* num_deleted */);
  149.   GURL url_;
  150.   mojo::Remote<network::mojom::CookieManager> store_browser_cookie_manager_;
  151.   absl::optional<api::cookies::Remove::Params> parsed_args_;
  152. };
  153. // Implements the cookies.getAllCookieStores() extension function.
  154. class CookiesGetAllCookieStoresFunction : public ExtensionFunction {
  155. public:
  156.   DECLARE_EXTENSION_FUNCTION("cookies.getAllCookieStores",
  157.                              COOKIES_GETALLCOOKIESTORES)
  158. protected:
  159.   ~CookiesGetAllCookieStoresFunction() override {}
  160.   // ExtensionFunction:
  161.   ResponseAction Run() override;
  162. };
  163. class CookiesAPI : public BrowserContextKeyedAPI, public EventRouter::Observer {
  164. public:
  165.   explicit CookiesAPI(content::BrowserContext* context);
  166.   CookiesAPI(const CookiesAPI&) = delete;
  167.   CookiesAPI& operator=(const CookiesAPI&) = delete;
  168.   ~CookiesAPI() override;
  169.   // KeyedService implementation.
  170.   void Shutdown() override;
  171.   // BrowserContextKeyedAPI implementation.
  172.   static BrowserContextKeyedAPIFactory<CookiesAPI>* GetFactoryInstance();
  173.   // EventRouter::Observer implementation.
  174.   void OnListenerAdded(const EventListenerInfo& details) override;
  175. private:
  176.   friend class BrowserContextKeyedAPIFactory<CookiesAPI>;
  177.   raw_ptr<content::BrowserContext> browser_context_;
  178.   // BrowserContextKeyedAPI implementation.
  179.   static const char* service_name() {
  180.     return "CookiesAPI";
  181.   }
  182.   static const bool kServiceIsNULLWhileTesting = true;
  183.   // Created lazily upon OnListenerAdded.
  184.   std::unique_ptr<CookiesEventRouter> cookies_event_router_;
  185. };
  186. }  // namespace extensions
  187. #endif  // CHROME_BROWSER_EXTENSIONS_API_COOKIES_COOKIES_API_H_
复制代码
三、开辟者模式打开加载下扩展看下堆栈结果:
     

至此分析完毕,如果想拦截 chrome.cookies.getAll等方法在  chrome\browser\extensions\api\cookies\cookies_api.cc中更改即可。
回复

使用道具 举报

登录后关闭弹窗

登录参与点评抽奖  加入IT实名职场社区
去登录
快速回复 返回顶部 返回列表