Chromium 关闭 Google Chrome 后继续运行后台应用功能分析c++

此功能允许关闭 Google Chrome 后继续运行后台,控制此功能的开关是

// Set to true if background mode is enabled on this browser.

//更改此值可以修改默认开启关闭

inline constexpr char kBackgroundModeEnabled[] = "background_mode.enabled";

chrome\browser\background\background_mode_manager.cc

// staticvoid BackgroundModeManager::RegisterPrefs(PrefRegistrySimple* registry) {//更改此值可以修改默认开启关闭registry->RegisterBooleanPref(prefs::kBackgroundModeEnabled, true);}

1、此功能前端代码

chrome\browser\resources\settings\system_page\system_page.html

<if expr="not is_macosx and not chromeos_lacros"><settings-toggle-buttonpref="{{prefs.background_mode.enabled}}" //监听prefs变化label="$i18n{backgroundAppsLabel}"></settings-toggle-button><div class="hr"></div>
</if>

2、c++对应kBackgroundModeEnabled监听实现代码

chrome\browser\background\background_mode_manager.cc

///
//  BackgroundModeManager, public
BackgroundModeManager::BackgroundModeManager(const base::CommandLine& command_line,ProfileAttributesStorage* profile_storage): profile_storage_(profile_storage), task_runner_(CreateTaskRunner()) {// We should never start up if there is no browser process or if we are// currently quitting.CHECK(g_browser_process);CHECK(!browser_shutdown::IsTryingToQuit());// Add self as an observer for the ProfileAttributesStorage so we know when// profiles are deleted and their names change.// This observer is never unregistered because the BackgroundModeManager// outlives the profile storage.profile_storage_->AddObserver(this);// Listen for the background mode preference changing.if (g_browser_process->local_state()) {  // Skip for unit testspref_registrar_.Init(g_browser_process->local_state());pref_registrar_.Add(prefs::kBackgroundModeEnabled, //监听prefs变化,控制功能开启关闭base::BindRepeating(&BackgroundModeManager::OnBackgroundModeEnabledPrefChanged,base::Unretained(this)));}}

3、允许前端更改prefs值需要加白在

chrome\browser\extensions\api\settings_private\prefs_util.cc

const PrefsUtil::TypedPrefMap& PrefsUtil::GetAllowlistedKeys(){// System settings.(*s_allowlist)[::prefs::kBackgroundModeEnabled] =settings_api::PrefType::kBoolean;}

=========================================================================

注意:以下是前端更改prefs过程

     前端通过chrome.settingsPrivate.setPref接口 通过mojom发送给主进程chrome\browser\extensions\api\settings_private\settings_private_api.h接口进行设置。

c++如何定义一个chrome.settingsPrivate接口给前端调用呢?

1、接口定义chrome\common\extensions\api\settings_private.idl

// Copyright 2015 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.// Use the <code>chrome.settingsPrivate</code> API to get or set preferences
// from the settings UI. Access is restricted to a set of allowed user facing
// preferences.
namespace settingsPrivate {enum PrefType { BOOLEAN, NUMBER, STRING, URL, LIST, DICTIONARY };enum ControlledBy {DEVICE_POLICY,USER_POLICY,OWNER,PRIMARY_USER,EXTENSION,// Preferences are controlled by the parent of the child user.PARENT,// Preferences are controlled neither by parent nor the child user.// Preference values are hard-coded values and can not be changed.CHILD_RESTRICTION};enum Enforcement {// Value cannot be changed by user.ENFORCED,// Value can be changed, but the administrator recommends a default.RECOMMENDED,// Value is protected by a code that only parents can access. The logic to// require the code is NOT automatically added to a preference using this// enforcement. This is only used to display the correct pref indicator.PARENT_SUPERVISED};dictionary PrefObject {// The key for the pref.DOMString key;// The type of the pref (e.g., boolean, string, etc.).PrefType type;// The current value of the pref.any? value;// The policy source of the pref; an undefined value means there is no// policy.ControlledBy? controlledBy;// The owner name if controlledBy == OWNER.// The primary user name if controlledBy == PRIMARY_USER.// The extension name if controlledBy == EXTENSION.DOMString? controlledByName;// The policy enforcement of the pref; must be specified if controlledBy is// also present.Enforcement? enforcement;// The recommended value if enforcement == RECOMMENDED.any? recommendedValue;// If enforcement == ENFORCED this optionally specifies preference values// that are still available for selection by the user. If set, must contain// at least 2 distinct values, as must contain |value| and// |recommendedValue| (if present).any[]? userSelectableValues;// If true, user control of the preference is disabled for reasons unrelated// to controlledBy (e.g. no signed-in profile is present). A false value is// a no-op.boolean? userControlDisabled;// The extension ID if controlledBy == EXTENSION.DOMString? extensionId;// Whether the controlling extension can be disabled if controlledBy ==// EXTENSION.boolean? extensionCanBeDisabled;};callback OnPrefSetCallback = void (boolean success);callback GetAllPrefsCallback = void (PrefObject[] prefs);callback GetPrefCallback = void (PrefObject pref);callback GetDefaultZoomCallback = void (double zoom);callback SetDefaultZoomCallback = void (boolean success);interface Functions {// Sets a pref value.// |name|: The name of the pref.// |value|: The new value of the pref.// |pageId|: An optional user metrics identifier.// |callback|: The callback for whether the pref was set or not.[supportsPromises] static void setPref(DOMString name,any value,optional DOMString pageId,optional OnPrefSetCallback callback);// Gets an array of all the prefs.[supportsPromises] static void getAllPrefs(GetAllPrefsCallback callback);// Gets the value of a specific pref.[supportsPromises] static void getPref(DOMString name,GetPrefCallback callback);// Gets the default page zoom factor. Possible values are currently between// 0.25 and 5. For a full list, see zoom::kPresetZoomFactors.[supportsPromises] static void getDefaultZoom(GetDefaultZoomCallback callback);// Sets the page zoom factor. Must be less than 0.001 different than a value// in zoom::kPresetZoomFactors.[supportsPromises] static void setDefaultZoom(double zoom,optional SetDefaultZoomCallback callback);};interface Events {// Fired when a set of prefs has changed.//// |prefs| The prefs that changed.static void onPrefsChanged(PrefObject[] prefs);};
};

2、c++settingsPrivate接口实现

chrome\browser\extensions\api\settings_private\settings_private_api.h

// Copyright 2015 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_SETTINGS_PRIVATE_SETTINGS_PRIVATE_API_H_
#define CHROME_BROWSER_EXTENSIONS_API_SETTINGS_PRIVATE_SETTINGS_PRIVATE_API_H_#include "extensions/browser/extension_function.h"namespace extensions {// Implements the chrome.settingsPrivate.setPref method.
class SettingsPrivateSetPrefFunction : public ExtensionFunction {public:SettingsPrivateSetPrefFunction() {}SettingsPrivateSetPrefFunction(const SettingsPrivateSetPrefFunction&) =delete;SettingsPrivateSetPrefFunction& operator=(const SettingsPrivateSetPrefFunction&) = delete;DECLARE_EXTENSION_FUNCTION("settingsPrivate.setPref", SETTINGSPRIVATE_SETPREF)protected:~SettingsPrivateSetPrefFunction() override;// ExtensionFunction overrides.ResponseAction Run() override;
};// Implements the chrome.settingsPrivate.getAllPrefs method.
class SettingsPrivateGetAllPrefsFunction : public ExtensionFunction {public:SettingsPrivateGetAllPrefsFunction() {}SettingsPrivateGetAllPrefsFunction(const SettingsPrivateGetAllPrefsFunction&) = delete;SettingsPrivateGetAllPrefsFunction& operator=(const SettingsPrivateGetAllPrefsFunction&) = delete;DECLARE_EXTENSION_FUNCTION("settingsPrivate.getAllPrefs",SETTINGSPRIVATE_GETALLPREFS)protected:~SettingsPrivateGetAllPrefsFunction() override;// ExtensionFunction overrides.ResponseAction Run() override;
};// Implements the chrome.settingsPrivate.getPref method.
class SettingsPrivateGetPrefFunction : public ExtensionFunction {public:SettingsPrivateGetPrefFunction() {}SettingsPrivateGetPrefFunction(const SettingsPrivateGetPrefFunction&) =delete;SettingsPrivateGetPrefFunction& operator=(const SettingsPrivateGetPrefFunction&) = delete;DECLARE_EXTENSION_FUNCTION("settingsPrivate.getPref", SETTINGSPRIVATE_GETPREF)protected:~SettingsPrivateGetPrefFunction() override;// ExtensionFunction overrides.ResponseAction Run() override;
};// Implements the chrome.settingsPrivate.getDefaultZoom method.
class SettingsPrivateGetDefaultZoomFunction : public ExtensionFunction {public:SettingsPrivateGetDefaultZoomFunction() {}SettingsPrivateGetDefaultZoomFunction(const SettingsPrivateGetDefaultZoomFunction&) = delete;SettingsPrivateGetDefaultZoomFunction& operator=(const SettingsPrivateGetDefaultZoomFunction&) = delete;DECLARE_EXTENSION_FUNCTION("settingsPrivate.getDefaultZoom",SETTINGSPRIVATE_GETDEFAULTZOOMFUNCTION)protected:~SettingsPrivateGetDefaultZoomFunction() override;// ExtensionFunction overrides.ResponseAction Run() override;
};// Implements the chrome.settingsPrivate.setDefaultZoom method.
class SettingsPrivateSetDefaultZoomFunction : public ExtensionFunction {public:SettingsPrivateSetDefaultZoomFunction() {}SettingsPrivateSetDefaultZoomFunction(const SettingsPrivateSetDefaultZoomFunction&) = delete;SettingsPrivateSetDefaultZoomFunction& operator=(const SettingsPrivateSetDefaultZoomFunction&) = delete;DECLARE_EXTENSION_FUNCTION("settingsPrivate.setDefaultZoom",SETTINGSPRIVATE_SETDEFAULTZOOMFUNCTION)protected:~SettingsPrivateSetDefaultZoomFunction() override;// ExtensionFunction overrides.ResponseAction Run() override;
};}  // namespace extensions#endif  // CHROME_BROWSER_EXTENSIONS_API_SETTINGS_PRIVATE_SETTINGS_PRIVATE_API_H_

3、在extensions\browser\extension_function_histogram_value.h中定义函数ID

  注意extensions\browser\extension_function_histogram_value.h中与chrome\browser\extensions\api\settings_private\settings_private_api.h中类名的对应关系,否则关联失败。//SETTINGSPRIVATE_SETPREF 应是类名(SettingsPrivateSetPrefFunction)去掉Function之后大写!!!!!

4、该类注册在out\Debug\gen\chrome\browser\extensions\api\generated_api_registration.cc

   [自动生成的代码,不需要手动添加]

namespace extensions {
namespace api {// static
void ChromeGeneratedFunctionRegistry::RegisterAll(ExtensionFunctionRegistry* registry)
{   {&NewExtensionFunction<SettingsPrivateSetPrefFunction>,SettingsPrivateSetPrefFunction::static_function_name(),SettingsPrivateSetPrefFunction::static_histogram_value(),},........................................
}

5、注册api地方 chrome\browser\extensions\chrome_extensions_browser_api_provider.cc

namespace extensions {ChromeExtensionsBrowserAPIProvider::ChromeExtensionsBrowserAPIProvider() =default;
ChromeExtensionsBrowserAPIProvider::~ChromeExtensionsBrowserAPIProvider() =default;void ChromeExtensionsBrowserAPIProvider::RegisterExtensionFunctions(ExtensionFunctionRegistry* registry) {// Preferences.registry->RegisterFunction<GetPreferenceFunction>();registry->RegisterFunction<SetPreferenceFunction>();registry->RegisterFunction<ClearPreferenceFunction>();// Generated APIs from Chrome.api::ChromeGeneratedFunctionRegistry::RegisterAll(registry);
}}  // namespace extensions

6、前端获取prefs实现

base::Value::List SettingsPrivateDelegate::GetAllPrefs() {base::Value::List prefs;//GetAllowlistedKeys()定义在//chrome\browser\extensions\api\settings_private\prefs_util.cc//所以要给前端添加新的prefs监听 要在此处加白,否则前端获取不到该prefs值const TypedPrefMap& keys = prefs_util_->GetAllowlistedKeys();for (const auto& it : keys) {if (absl::optional<base::Value::Dict> pref = GetPref(it.first); pref) {prefs.Append(std::move(*pref));}}return prefs;
}

7、最后将settings_private.idl 放到chrome\common\extensions\api\api_sources.gni 

中,然后进行编译即可。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.rhkb.cn/news/444742.html

如若内容造成侵权/违法违规/事实不符,请联系长河编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

前端的全栈混合之路Meteor篇:分布式数据协议DDP深度剖析

本文属于进阶篇&#xff0c;并不是太适合新人阅读&#xff0c;但纯粹的学习还是可以的&#xff0c;因为后续会实现很多个ddp的版本用于web端、nodejs端、安卓端和ios端&#xff0c;提前预习和复习下。ddp协议是一个C/S架构的协议&#xff0c;但是客户端也同时可以是服务端。 什…

STM32F407寄存器操作(DMA+SPI)

1.前言 前面看B站中有些小伙伴吐槽F4的SPIDMA没有硬件可控的CS引脚&#xff0c;那么今天我就来攻破这个问题 我这边暂时没有SPI的从机芯片&#xff0c;并且接收的过程与发送的过程类似&#xff0c;所以这里我就以发送的过程为例了。 2.理论 手册上给出了如下的描述 我们关注…

Spring Boot 学习之路 -- Thymeleaf 模板引擎

前言 最近因为业务需要&#xff0c;被拉去研究后端的项目&#xff0c;代码框架基于 Spring Boot&#xff0c;后端对我来说完全小白&#xff0c;需要重新学习研究…出于个人习惯&#xff0c;会以 Blog 文章的方式做一些记录&#xff0c;文章内容基本来源于「 Spring Boot 从入门…

微信小程序-分包加载

一.分包的意义 小程序是由多个页面构成&#xff0c;为了因为代码量多&#xff0c;体积大导致用户打开速度变慢&#xff0c;小程序提供了分包加载数据。 分包加载数据&#xff0c;只有在主包调用分包某一个页面时候才会调用加载分包。即就是按需加载。 整个小程序不能超过20M&a…

golang grpc进阶

protobuf 官方文档 基本数据类型 .proto TypeNotesGo Typedoublefloat64floatfloat32int32使用变长编码&#xff0c;对于负值的效率很低&#xff0c;如果你的域有可能有负值&#xff0c;请使用sint64替代int32uint32使用变长编码uint32uint64使用变长编码uint64sint32使用变长…

滚柱导轨适配技巧与注意事项!

滚柱导轨是一种重要的传动元件&#xff0c;它由滚柱作为滚动体。用于连接机床的运动部件和床身基座&#xff0c;其设计旨在提供高承载能力和高刚度&#xff0c;适用于重型机床和精密仪器&#xff0c;而滚柱导轨的适配方法对于确保机械设备的高精度运行至关重要。 滚柱导轨的适配…

大数据分析案例-基于逻辑回归算法构建抑郁非抑郁推文识别模型

🤵‍♂️ 个人主页:@艾派森的个人主页 ✍🏻作者简介:Python学习者 🐋 希望大家多多支持,我们一起进步!😄 如果文章对你有帮助的话, 欢迎评论 💬点赞👍🏻 收藏 📂加关注+ 喜欢大数据分析项目的小伙伴,希望可以多多支持该系列的其他文章 大数据分析案例合集

介绍Java

Java简介 Java是一门由Sun公司&#xff08;现被Oracle收购&#xff09;在1995年开发的计算机编程语言&#xff0c;其主力开发人员是James Gosling&#xff0c;被称为Java之父。Java在被命名为“Java”之前&#xff0c;实际上叫做Oak&#xff0c;这个名字源于James Gosling望向…

Unite Barcelona主题演讲回顾:深入了解 Unity 6

本周&#xff0c;来自世界各地的 Unity 开发者齐聚西班牙巴塞罗那&#xff0c;参加 Unite 2024。本次大会的主题演讲持续了一个多小时&#xff0c;涵盖新功能的介绍、开发者成功案例的分享&#xff0c;以及在编辑器中进行的技术演示&#xff0c;重点展示了 Unity 6 在实际项目中…

学习python自动化——pytest单元测试框架

一、什么是pytest 单元测试框架&#xff0c;unittest&#xff08;python自带的&#xff09;&#xff0c;pytest&#xff08;第三方库&#xff09;。 用于编写测试用例、收集用例、执行用例、生成测试结果文件&#xff08;html、xml&#xff09; 1.1、安装pytest pip instal…

Spring AI 介绍与入门使用 -- 一个Java版Langchain

Langchain 是什么&#xff1f; Langchain 是一个Python 的AI开发框架&#xff0c;它集成了模型输入输出、检索、链式调用、内存记忆&#xff08;Memory&#xff09;、Agents以及回调函数等功能模块。通过这些模块的协同工作&#xff0c;它能够支持复杂的对话场景和任务执行流程…

C语言 | Leetcode C语言题解之第460题LFU缓存

题目&#xff1a; 题解&#xff1a; /* 数值链表的节点定义。 */ typedef struct ValueListNode_s {int key;int value;int counter;struct ValueListNode_s *prev;struct ValueListNode_s *next; } ValueListNode;/* 计数链表的节点定义。 其中&#xff0c;head是数值链表的头…

多点低压差分(M-LVDS)线路驱动器和接收器——MS2111

MS2111 是多点低压差分 (M-LVDS) 线路驱动器和接收器。经过 优化&#xff0c;可运行在高达 200Mbps 的信号速率下。所有部件均符合 M LVDS 标准 TIA / EIA-899 。该驱动器的输出支持负载低至 30Ω 的多 点总线。 MS2111 的接收器属于 Type-2 &#xff0c; 可在 -1…

【GESP】C++一级练习BCQM3037,简单计算,国庆七天乐收官

又回到了简单计算的题目&#xff0c;继续巩固练习。 题解详见&#xff1a;https://www.coderli.com/gesp-1-bcqm3037/ 【GESP】C一级练习BCQM3037&#xff0c;简单计算&#xff0c;国庆七天乐收官 | OneCoder又回到了简单计算的题目&#xff0c;继续巩固练习。https://www.cod…

性能测试工具locust —— Python脚本参数化!

1.1.登录用户参数化 在测试过程中&#xff0c;经常会涉及到需要用不同的用户登录操作&#xff0c;可以采用队列的方式&#xff0c;对登录的用户进行参数化。如果数据要保证不重复&#xff0c;则取完不再放回&#xff1b;如可以重复&#xff0c;则取出后再返回队列。 def lo…

std::future::then的概念和使用方法

std::future::then是 C 中用于异步操作的一种机制&#xff0c;它允许在一个异步任务完成后&#xff0c;接着执行另一个操作&#xff08;即延续操作&#xff09;。以下是关于 std::future::then 的概念和使用方法&#xff1a; 1. 概念&#xff1a; std::future::then 的主要目…

Chrome清除nslookup解析记录 - 强制http访问 - 如何禁止chrome 强制跳转https

步骤&#xff1a; 地址栏输入 chrome://net-internals/#hsts在Delete domain 栏的输入框中输入要http访问的域名&#xff0c;然后点击“delete”按钮最后在Query domain 栏中搜索刚才输入的域名&#xff0c;点击“query”按钮后如果提示“Not found”即可&#xff01; 办法来自…

Java | Leetcode Java题解之第459题重复的子字符串

题目&#xff1a; 题解&#xff1a; class Solution {public boolean repeatedSubstringPattern(String s) {return kmp(s s, s);}public boolean kmp(String query, String pattern) {int n query.length();int m pattern.length();int[] fail new int[m];Arrays.fill(fa…

Hunuan-DiT代码阅读

一 整体架构 该模型是以SD为基础的文生图模型&#xff0c;具体扩散模型原理参考https://zhouyifan.net/2023/07/07/20230330-diffusion-model/&#xff0c;代码地址https://github.com/Tencent/HunyuanDiT&#xff0c;这里介绍 Full-parameter Training 二 输入数据处理 这里…

E系列I/O模块在锂电装备制造系统的应用

为了满足电池生产线对稳定性和生产效率的严苛要求&#xff0c;ZLG致远电子推出高速I/O应用方案&#xff0c;它不仅稳定可靠&#xff0c;而且速度快&#xff0c;能够迅速响应生产需求。 锂电池的生产工艺较为复杂&#xff0c;大致分为三个主要阶段&#xff1a;极片制作、电芯制作…