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

news2024/10/5 4:54:47

此功能允许关闭 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

// static

void 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-button
        pref="{{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 tests
    pref_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.coloradmin.cn/o/2189275.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

Python爬虫(五)--爬虫库的使用(Python Crawler (5) - Use of Crawler Libraries)

&#x1f49d;&#x1f49d;&#x1f49d;欢迎来到我的博客&#xff0c;很高兴能够在这里和您见面&#xff01;希望您在这里可以感受到一份轻松愉快的氛围&#xff0c;不仅可以获得有趣的内容和知识&#xff0c;也可以畅所欲言、分享您的想法和见解。 本人主要分享计算机核心技…

如何解决在 nextjs 中使用 sequelize 连接 mysql 报错:Please install mysql2 package manually

解决方案 手动设置 dialectModule 的值为 mysql2。增加 dialectModule 配置即可。 import mysql2 from mysql2 import { Sequelize } from sequelizeconst { DB_DATABASE, DB_USER, DB_PASSWORD, DB_HOST, DB_PORT, DB_LOGGING, DB_POLL_MAX, DB_POLL_MIN, DB_POLL_ACQUIRE, …

Android Framework(八)WMS-窗口动效概述

文章目录 动画简述本地、远端动画的定义什么是“leash”图层“leash”图层的命令与创建 Winscope流程小结 动画流程概览分析Activity启动app_transition 动画的主要事件触发动画执行的套路动画真正执行动画的结束回调触发远端动画的Target 动画简述 1、动画的原理也是利用了视觉…

vue3 + Ant design vue formItem 无法使用嵌套的form表单校验

文章目录 前言一、背景在这里插入代码片二、操作步骤1.复现前的准备工作&#xff08;1&#xff09;vue版本和ant design vue 版本&#xff08;2&#xff09;任意页面的代码 2.解决问题3.自定义表单校验的代码 总结 前言 提示&#xff1a; 一、背景在这里插入代码片 背景&…

音视频入门基础:FLV专题(13)——FFmpeg源码中,解析任意Type值的SCRIPTDATAVALUE类型的实现

一、SCRIPTDATAVALUE类型 从《音视频入门基础&#xff1a;FLV专题&#xff08;9&#xff09;——Script Tag简介》中可以知道&#xff0c;根据《video_file_format_spec_v10_1.pdf》第80到81页&#xff0c;SCRIPTDATAVALUE类型由一个8位&#xff08;1字节&#xff09;的Type和…

go语言protoc的详细用法与例子

一. 原来的项目结构 二. 选择源proto文件及其目录&目的proto文件及其目录 在E:\code\go_test\simple_demo\api 文件夹下&#xff0c;递归创建\snapshot\helloworld\v1\ad.pb.go E:\code\go_test\simple_demo> protoc --go_outpathssource_relative:./api .\snapshot\h…

数据结构--二叉树的顺序实现(堆实现)

引言 在计算机科学中&#xff0c;二叉树是一种重要的数据结构&#xff0c;广泛应用于各种算法和程序设计中。本文将探讨二叉树的顺序实现&#xff0c;特别是堆的实现方式。 一、树 1.1树的概念与结构 树是⼀种⾮线性的数据结构&#xff0c;它是由 n(n>0) 个有限结点组成…

新款平行进口奔驰GLS450升级原厂AR实景导航人机交互行车记录仪等功能

平行进口的24款奔驰GLS450升级原厂中规导航主机通常具备以下功能&#xff1a; 人机交互系统&#xff1a;该导航主机配备了人机交互系统&#xff0c;可以通过触摸屏、旋钮或语音控制等方式与导航系统进行交互&#xff0c;方便驾驶者进行导航设置和操作。 实景AR导航&#xff1…

使用 classification_report 评估 scikit-learn 中的分类模型

介绍 在机器学习领域&#xff0c;评估分类模型的性能至关重要。scikit-learn 是一个功能强大的 Python 机器学习工具&#xff0c;提供了多种模型评估工具。其中最有用的函数之一是 classification_report&#xff0c;它可以全面概述分类模型的关键指标。在这篇文章中&#xff…

字符串和字符数组(1)

1.字符串和\0 C语言中有字符类型&#xff0c;但没有字符串类型&#xff0c;C语言中字符串就是由双引号引起来的一串字符&#xff0c;比如&#xff1a;"asdf"&#xff1b; 一个字符串中我们能直观的看到一些字符&#xff0c;比如&#xff1a;字符串常量"asdfgh…

三、Java AI 编程助手

AI 对于我们来说是一个高效的编程助手&#xff0c;给我们提供了有效的建议和解决方案&#xff0c;高效利用&#xff0c;无疑是如虎添翼。接下来为大家推荐一个 AI 编程助手。 Fitten Code 1、简介 Fitten Code 免费且支持 80 多种语言&#xff1a;Python、C、Javascript、Type…

2024.9.29 问卷数据分析

最近拿到了一份受众回访的问卷数据&#xff0c;排到的任务是对它进行数据探索。 其实对于问卷数据的处理我只在参加正大杯那次做过&#xff08;正大杯拿了校三&#xff09;&#xff0c;可见这个处理水平还有待提高&#xff08;当然是各种原因促成的结果&#xff09;&#xff0…

python配置环境变量

方法一&#xff1a;首先卸载重新安装&#xff0c;在安装时勾选增加环境变量 方法二&#xff1a;我的电脑-属性-高级系统配置 手动添加环境变量&#xff0c;路径为python的安装路径 检查&#xff1a;查看环境变量是否安装成功 安装第三方lib winr&#xff0c;输入cmd pip ins…

[SAP ABAP] 数据元素添加参数ID(Parameter ID)

学生表(ZDBT_STU_437) 示例&#xff1a;为学生表ZDBT_STU_437中的数据元素ZDE_STUID_437创建Parameter ID 1.使用事务码SM30维护TPARA表 新建参数ID并输入简短描述 点击保存按钮&#xff0c;选择指定的包即可生成参数ID 2.参数ID和数据元素绑定 使用SE11对学生表(ZDBT_STU_…

小程序 uniapp+Android+hbuilderx体育场地预约管理系统的设计与实现

目录 项目介绍支持以下技术栈&#xff1a;具体实现截图HBuilderXuniappmysql数据库与主流编程语言java类核心代码部分展示登录的业务流程的顺序是&#xff1a;数据库设计性能分析操作可行性技术可行性系统安全性数据完整性软件测试详细视频演示源码获取方式 项目介绍 用户 注册…

【ubuntu】ubuntu20.04安装chrome浏览器

1.下载 https://download.csdn.net/download/qq_35975447/89842972 https://www.google.cn/chrome/ 2.安装 sudo dpkg -i google-chrome-stable_current_amd64.deb 3.使用

vscode配置R语言debugger环境:“vscDebugger“的安装

要在 R 中安装 vscDebugger 包&#xff0c;可以按照以下步骤进行&#xff1a; 方法一&#xff1a;使用命令面板自动安装 打开命令面板&#xff1a; 在 Visual Studio Code 中按 CtrlShiftP 打开命令面板。 运行安装命令&#xff1a; 在命令面板中输入并选择 r.debugger.updat…

DES算法的详细描述和C语言实现

访问www.tomcoding.com网站&#xff0c;学习Oracle内部数据结构&#xff0c;详细文档说明&#xff0c;下载Oracle的exp/imp&#xff0c;DUL&#xff0c;logminer&#xff0c;ASM工具的源代码&#xff0c;学习高技术含量的内容。 前言 很久以前用汇编语言实现过DES算法&#x…

UE4 材质学习笔记02(数据类型/扭曲着色器)

一.什么是数据类型 首先为啥理解数据类型是很重要的。一些节点的接口插槽只接受特定类型的数据&#xff0c;如果连接了不匹配的数据就会出现错误&#xff0c;有些接口可以接受任何数据类型&#xff0c;但是实际上只会使用到其中的一些。并且有时可以将多个数据流合并成一个来编…

《python语言程序设计》2018版第8章19题几何Rectangle2D类(上)--原来我可以直接调用

2024.9.29 玩了好几天游戏。 感觉有点灵感了。还想继续玩游戏。 2024.10.4 今天练习阿斯汤加练完从早上10点睡到下午2点.跑到单位玩游戏玩到晚上10点多. 现在回家突然有了灵感 顺便说一句,因为后弯不好,明天加练一次. 然后去丈母娘家. 加油吧 第一章、追求可以外调的函数draw_r…