chrome.runtime

  • 描述

    使用chrome.runtimeAPI 检索后台页面,返回有关清单的详细信息,以及侦听和响应应用程序或扩展生命周期中的事件。您还可以使用此 API 将 URL 的相对路径转换为完全限定的 URL。

运行时 API 提供了一些方法来支持您的扩展可以使用的许多功能领域:

消息传递
这些方法支持消息传递,以便您可以与扩展程序的不同部分(例如扩展程序弹出窗口和后台脚本)、其他扩展程序或用户设备上的本机应用程序进行通信。有关该主题的概述,请参阅 消息传递。 此类别中的方法包括 connectconnectNativesendMessagesendNativeMessage
访问扩展和平台元数据
这些方法使您可以检索有关扩展和平台的若干特定元数据。此类别中的方法包括 getBackgroundPagegetManifestgetPackageDirectoryEntrygetPlatformInfo
管理扩展生命周期和选项
这些方法让您可以对扩展执行一些元操作,并向扩展用户显示选项页面。此类别中的方法包括 reloadrequestUpdateChecksetUninstallURLopenOptionsPage
设备重启支持
这些方法仅在 Chrome 操作系统上可用,并且主要用于支持信息亭实现。此类别中的方法包括 restartrestartAfterDelay
辅助实用程序
这些方法提供了实用程序,例如将内部资源表示转换为外部格式。此类别中的方法包括 getURL

#显现

运行时 API 上的大多数方法不需要任何权限即可使用。但是,sendNativeMessageconnectNative需要nativeMessaging在清单中声明权限。

#例子

#用于getURL向页面添加扩展图像

为了让网页访问托管在另一个域上的资产,它必须指定资源的完整 URL(例如<img src="https://example.com/logo.png">)。当网页想要包含扩展中包含的资产时也是如此。这里的两个主要区别是扩展的资产必须作为Web 可访问资源公开,并且通常内容脚本负责注入扩展资产。

此示例显示内容脚本如何将扩展包中的图像添加到内容脚本已注入的页面。

 content.js 

{ // Block used to avoid setting global variables
const img = document.createElement('img');
img.src = chrome.runtime.getURL('logo.png');
document.body.append(img);
}

#将背景数据放入内容脚本

扩展的内容脚本通常需要由扩展的另一部分管理的数据,例如扩展的后台脚本。就像打开同一个网页的两个浏览器窗口一样,这两个上下文不能直接访问彼此的值。相反,扩展可以使用消息传递来协调这些不同的上下文。

在这个例子中,内容脚本需要一些来自扩展后台脚本的数据来初始化它的 UI。为获取此数据,它get-user-data向后台传递一条消息,后台以用户信息的副本进行响应。

 content.js 

// 1. Send the background a message requesting the user's data
chrome.runtime.sendMessage('get-user-data', (response) => {
// 3. Got an asynchronous response with the data from the background
console.log('received user data', response);
initializeUI(response);
});
 background.js 

// Example of a simple user data object
const user = {
username: 'demo-user'
};

chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
// 2. A page requested user data, respond with a copy of `user`
if (message === 'get-user-data') {
sendResponse(user);
}
});

#收集卸载反馈

许多扩展程序使用卸载后调查来了解扩展程序如何更好地为其用户服务并提高保留率。下面的示例显示了如何将此功能添加到他们的扩展中。

chrome.runtime.onInstalled.addListener(details => {
if (details.reason === chrome.runtime.OnInstalledReason.INSTALL) {
chrome.runtime.setUninstallURL('https://example.com/extension-survey');
}
});

概括

Types

MessageSender

An object containing information about the script context that sent a message or request.

Properties
  • frameId

    number optional

    The frame that opened the connection. 0 for top-level frames, positive for child frames. This will only be set when tab is set.

  • id

    string optional

    The ID of the extension or app that opened the connection, if any.

  • nativeApplication

    string optional

    Chrome 74+

    The name of the native application that opened the connection, if any.

  • origin

    string optional

    Chrome 80+

    The origin of the page or frame that opened the connection. It can vary from the url property (e.g., about:blank) or can be opaque (e.g., sandboxed iframes). This is useful for identifying if the origin can be trusted if we can't immediately tell from the URL.

  • tab

    Tab optional

    The tabs.Tab which opened the connection, if any. This property will only be present when the connection was opened from a tab (including content scripts), and only if the receiver is an extension, not an app.

  • tlsChannelId

    string optional

    The TLS channel ID of the page or frame that opened the connection, if requested by the extension or app, and if available.

  • url

    string optional

    The URL of the page or frame that opened the connection. If the sender is in an iframe, it will be iframe's URL not the URL of the page which hosts it.

OnInstalledReason

Chrome 44+

The reason that this event is being dispatched.

Type

"install"

,

"update"

,

"chrome_update"

, or

"shared_module_update"

OnRestartRequiredReason

Chrome 44+

The reason that the event is being dispatched. 'app_update' is used when the restart is needed because the application is updated to a newer version. 'os_update' is used when the restart is needed because the browser/OS is updated to a newer version. 'periodic' is used when the system runs for more than the permitted uptime set in the enterprise policy.

Type

"app_update"

,

"os_update"

, or

"periodic"

PlatformArch

Chrome 44+

The machine's processor architecture.

Type

"arm"

,

"arm64"

,

"x86-32"

,

"x86-64"

,

"mips"

, or

"mips64"

PlatformInfo

An object containing information about the current platform.

Properties
  • The machine's processor architecture.

  • nacl_arch

    The native client architecture. This may be different from arch on some platforms.

  • The operating system Chrome is running on.

PlatformNaclArch

Chrome 44+

The native client architecture. This may be different from arch on some platforms.

Type

"arm"

,

"x86-32"

,

"x86-64"

,

"mips"

, or

"mips64"

PlatformOs

Chrome 44+

The operating system Chrome is running on.

Type

"mac"

,

"win"

,

"android"

,

"cros"

,

"linux"

, or

"openbsd"

Port

An object which allows two way communication with other pages. See Long-lived connections for more information.

Properties
  • name

    string

    The name of the port, as specified in the call to runtime.connect.

  • onDisconnect

    event

    Fired when the port is disconnected from the other end(s). runtime.lastError may be set if the port was disconnected by an error. If the port is closed via disconnect, then this event is only fired on the other end. This event is fired at most once (see also Port lifetime).

    The onDisconnect.addListener function looks like: (callback: function) => {...}

    • callback

      function

      The callback parameter looks like: (port: Port) => void

  • onMessage

    event

    This event is fired when postMessage is called by the other end of the port.

    The onMessage.addListener function looks like: (callback: function) => {...}

    • callback

      function

      The callback parameter looks like: (message: any, port: Port) => void

      • message

        any

      • port
  • sender

    MessageSender optional

    This property will only be present on ports passed to onConnect / onConnectExternal / onConnectNative listeners.

  • disconnect

    function

    Immediately disconnect the port. Calling disconnect() on an already-disconnected port has no effect. When a port is disconnected, no new events will be dispatched to this port.

    The disconnect function looks like: () => {...}

  • postMessage

    function

    Send a message to the other end of the port. If the port is disconnected, an error is thrown.

    The postMessage function looks like: (message: any) => {...}

    • message

      any

      Chrome 52+

      The message to send. This object should be JSON-ifiable.

RequestUpdateCheckStatus

Chrome 44+

Result of the update check.

Type

"throttled"

,

"no_update"

, or

"update_available"

Properties

id

The ID of the extension/app.

Type

string

lastError

This will be defined during an API method callback if there was an error

Type

object

Properties
  • message

    string optional

    Details about the error which occurred.

Methods

connect

chrome.runtime.connect(
  extensionId?: string,
  connectInfo?: object,
)

Attempts to connect to connect listeners within an extension/app (such as the background page), or other extensions/apps. This is useful for content scripts connecting to their extension processes, inter-app/extension communication, and web messaging. Note that this does not connect to any listeners in a content script. Extensions may connect to content scripts embedded in tabs via tabs.connect.

Parameters
  • extensionId

    string optional

    The ID of the extension or app to connect to. If omitted, a connection will be attempted with your own extension. Required if sending messages from a web page for web messaging.

  • connectInfo

    object optional

    • includeTlsChannelId

      boolean optional

      Whether the TLS channel ID will be passed into onConnectExternal for processes that are listening for the connection event.

    • name

      string optional

      Will be passed into onConnect for processes that are listening for the connection event.

Returns
  • Port through which messages can be sent and received. The port's onDisconnect event is fired if the extension/app does not exist.

connectNative

chrome.runtime.connectNative(
  application: string,
)

Connects to a native application in the host machine. See Native Messaging for more information.

Parameters
  • application

    string

    The name of the registered application to connect to.

Returns
  • Port through which messages can be sent and received with the application

getBackgroundPage

chrome.runtime.getBackgroundPage(
  callback?: function,
)
Promise Foreground only

Retrieves the JavaScript 'window' object for the background page running inside the current extension/app. If the background page is an event page, the system will ensure it is loaded before calling the callback. If there is no background page, an error is set.

Parameters
  • callback

    function optional

    The callback parameter looks like: (backgroundPage?: Window) => void

    • backgroundPage

      Window optional

      The JavaScript 'window' object for the background page.

Returns
  • Promise<Window | undefined>

    Pending

    This only returns a Promise when the callback parameter is not specified, and with MV3+. The type inside the Promise is the same as the 1st argument to callback.

getManifest

chrome.runtime.getManifest()

从清单中返回有关应用程序或扩展程序的详细信息。返回的对象是完整清单文件的序列化。

退货
  • 目的

    清单详细信息。

getPackageDirectoryEntry

chrome.runtime.getPackageDirectoryEntry(
  callback: function,
)
仅前景

返回包目录的 DirectoryEntry。

参数
  • 打回来

    功能

    callback参数如下所示:(directoryEntry: DirectoryEntry) => void

    • 目录项

      目录条目

获取平台信息

chrome.runtime.getPlatformInfo(
  callback?: function,
)
承诺

返回有关当前平台的信息。

参数
退货
  • 承诺< PlatformInfo >

    待办的

    这仅在未指定参数Promise时返回 a ,并且使用 MV3+。callback中的类型Promise与 的第一个参数相同callback

获取网址

chrome.runtime.getURL(
  path: string,
)

将应用程序/扩展安装目录中的相对路径转换为完全限定的 URL。

参数
  • 小路

    细绳

    相对于其安装目录表示的应用程序/扩展中资源的路径。

退货
  • 细绳

    资源的完全限定 URL。

打开选项页面

chrome.runtime.openOptionsPage(
  callback?: function,
)
承诺

如果可能,打开您的扩展程序的选项页面。

确切的行为可能取决于您的清单[options_ui](https://developer.chrome.com/docs/extensions/optionsV2)[options_page](https://developer.chrome.com/docs/extensions/options)密钥,或者 Chrome 当时支持的内容。例如,页面可以在新选项卡、chrome://extensions、应用程序中打开,或者它可能只关注打开的选项页面。它永远不会导致调用者页面重新加载。

如果您的扩展程序未声明选项页面,或者 Chrome 由于其他原因未能创建选项页面,则回调将设置lastError.

参数
  • 打回来

    功能 可选

    callback参数如下所示:() => void

退货
  • 承诺<无效>

    待办的

    这仅在未指定参数Promise时返回 a ,并且使用 MV3+。callback中的类型Promise与 的第一个参数相同callback

重新加载

chrome.runtime.reload()

重新加载应用程序或扩展程序。Kiosk 模式不支持此方法。对于信息亭模式,使用 chrome.runtime.restart() 方法。

请求更新检查

chrome.runtime.requestUpdateCheck(
  callback: function,
)

请求对此应用程序/扩展程序进行即时更新检查。

重要提示:大多数扩展程序/应用程序不应使用此方法,因为 Chrome 已经每隔几个小时进行一次自动检查,您可以在runtime.onUpdateAvailable无需调用 requestUpdateCheck 的情况下监听事件。

此方法只适合在非常有限的情况下调用,例如如果您的扩展程序/应用程序与后端服务对话,并且后端服务已确定客户端扩展程序/应用程序版本非常过时并且您想要提示用户更新。requestUpdateCheck 的大多数其他用途,例如基于重复计时器无条件地调用它,可能只会浪费客户端、网络和服务器资源。

参数
  • 打回来

    功能

    callback参数如下所示:(status: RequestUpdateCheckStatus, details?: object) => void

    • 更新检查的结果。

    • 细节

      对象 可选

      如果有可用更新,这将包含有关可用更新的更多信息。

      • 版本

        细绳

        可用更新的版本。

重新开始

chrome.runtime.restart()

当应用以自助服务终端模式运行时,重新启动 ChromeOS 设备。否则,它是无操作的。

restartAfterDelay

chrome.runtime.restartAfterDelay(
  seconds: number,
  callback?: function,
)
Promise Chrome 53+

Restart the ChromeOS device when the app runs in kiosk mode after the given seconds. If called again before the time ends, the reboot will be delayed. If called with a value of -1, the reboot will be cancelled. It's a no-op in non-kiosk mode. It's only allowed to be called repeatedly by the first extension to invoke this API.

Parameters
  • seconds

    number

    Time to wait in seconds before rebooting the device, or -1 to cancel a scheduled reboot.

  • callback

    function optional

    The callback parameter looks like: () => void

Returns
  • Promise<void>

    Pending

    This only returns a Promise when the callback parameter is not specified, and with MV3+. The type inside the Promise is the same as the 1st argument to callback.

sendMessage

chrome.runtime.sendMessage(
  extensionId?: string,
  message: any,
  options?: object,
  callback?: function,
)
Promise

Sends a single message to event listeners within your extension/app or a different extension/app. Similar to runtime.connect but only sends a single message, with an optional response. If sending to your extension, the runtime.onMessage event will be fired in every frame of your extension (except for the sender's frame), or runtime.onMessageExternal, if a different extension. Note that extensions cannot send messages to content scripts using this method. To send messages to content scripts, use tabs.sendMessage.

Parameters
  • extensionId

    string optional

    The ID of the extension/app to send the message to. If omitted, the message will be sent to your own extension/app. Required if sending messages from a web page for web messaging.

  • message

    any

    The message to send. This message should be a JSON-ifiable object.

  • options

    object optional

    • includeTlsChannelId

      boolean optional

      Whether the TLS channel ID will be passed into onMessageExternal for processes that are listening for the connection event.

  • callback

    function optional

    Chrome 99+

    The callback parameter looks like: (response: any) => void

    • response

      any

      The JSON response object sent by the handler of the message. If an error occurs while connecting to the extension, the callback will be called with no arguments and runtime.lastError will be set to the error message.

Returns
  • Promise<any>

    Pending

    This only returns a Promise when the callback parameter is not specified, and with MV3+. The type inside the Promise is the same as the 1st argument to callback.

sendNativeMessage

chrome.runtime.sendNativeMessage(
  application: string,
  message: object,
  callback?: function,
)
Promise

Send a single message to a native application.

Parameters
  • application

    string

    The name of the native messaging host.

  • message

    object

    The message that will be passed to the native messaging host.

  • callback

    function optional

    Chrome 99+

    The callback parameter looks like: (response: any) => void

    • response

      any

      The response message sent by the native messaging host. If an error occurs while connecting to the native messaging host, the callback will be called with no arguments and runtime.lastError will be set to the error message.

Returns
  • Promise<any>

    Pending

    This only returns a Promise when the callback parameter is not specified, and with MV3+. The type inside the Promise is the same as the 1st argument to callback.

setUninstallURL

chrome.runtime.setUninstallURL(
  url: string,
  callback?: function,
)
Promise

Sets the URL to be visited upon uninstallation. This may be used to clean up server-side data, do analytics, and implement surveys. Maximum 255 characters.

Parameters
  • url

    string

    URL to be opened after the extension is uninstalled. This URL must have an http: or https: scheme. Set an empty string to not open a new tab upon uninstallation.

  • callback

    function optional

    Chrome 45+

    The callback parameter looks like: () => void

Returns
  • Promise<void>

    Pending

    This only returns a Promise when the callback parameter is not specified, and with MV3+. The type inside the Promise is the same as the 1st argument to callback.

Events

onBrowserUpdateAvailable

chrome.runtime.onBrowserUpdateAvailable.addListener(
  callback: function,
)
Deprecated

Please use runtime.onRestartRequired.

Fired when a Chrome update is available, but isn't installed immediately because a browser restart is required.

Parameters
  • callback

    function

    The callback parameter looks like: () => void

onConnect

chrome.runtime.onConnect.addListener(
  callback: function,
)

Fired when a connection is made from either an extension process or a content script (by runtime.connect).

Parameters
  • callback

    function

    The callback parameter looks like: (port: Port) => void

onConnectExternal

chrome.runtime.onConnectExternal.addListener(
  callback: function,
)

Fired when a connection is made from another extension (by runtime.connect).

Parameters
  • callback

    function

    The callback parameter looks like: (port: Port) => void

onConnectNative

chrome.runtime.onConnectNative.addListener(
  callback: function,
)
Chrome 74+

Fired when a connection is made from a native application. Currently only supported on Chrome OS.

Parameters
  • callback

    function

    The callback parameter looks like: (port: Port) => void

onInstalled

chrome.runtime.onInstalled.addListener(
  callback: function,
)

Fired when the extension is first installed, when the extension is updated to a new version, and when Chrome is updated to a new version.

Parameters
  • callback

    function

    The callback parameter looks like: (details: object) => void

    • details

      object

      • id

        string optional

        Indicates the ID of the imported shared module extension which updated. This is present only if 'reason' is 'shared_module_update'.

      • previousVersion

        string optional

        Indicates the previous version of the extension, which has just been updated. This is present only if 'reason' is 'update'.

      • The reason that this event is being dispatched.

onMessage

chrome.runtime.onMessage.addListener(
  callback: function,
)

Fired when a message is sent from either an extension process (by runtime.sendMessage) or a content script (by tabs.sendMessage).

Parameters
  • callback

    function

    The callback parameter looks like: (message: any, sender: MessageSender, sendResponse: function) => boolean | undefined

    • message

      any

    • sender
    • sendResponse

      function

      The sendResponse parameter looks like: () => void

    • returns

      boolean | undefined

onMessageExternal

chrome.runtime.onMessageExternal.addListener(
  callback: function,
)

Fired when a message is sent from another extension/app (by runtime.sendMessage). Cannot be used in a content script.

Parameters
  • callback

    function

    The callback parameter looks like: (message: any, sender: MessageSender, sendResponse: function) => boolean | undefined

    • message

      any

    • sender
    • sendResponse

      function

      The sendResponse parameter looks like: () => void

    • returns

      boolean | undefined

onRestartRequired

chrome.runtime.onRestartRequired.addListener(
  callback: function,
)

Fired when an app or the device that it runs on needs to be restarted. The app should close all its windows at its earliest convenient time to let the restart to happen. If the app does nothing, a restart will be enforced after a 24-hour grace period has passed. Currently, this event is only fired for Chrome OS kiosk apps.

Parameters

onStartup

chrome.runtime.onStartup.addListener(
  callback: function,
)

Fired when a profile that has this extension installed first starts up. This event is not fired when an incognito profile is started, even if this extension is operating in 'split' incognito mode.

Parameters
  • callback

    function

    The callback parameter looks like: () => void

onSuspend

chrome.runtime.onSuspend.addListener(
  callback: function,
)

Sent to the event page just before it is unloaded. This gives the extension opportunity to do some clean up. Note that since the page is unloading, any asynchronous operations started while handling this event are not guaranteed to complete. If more activity for the event page occurs before it gets unloaded the onSuspendCanceled event will be sent and the page won't be unloaded.

Parameters
  • callback

    function

    The callback parameter looks like: () => void

onSuspendCanceled

chrome.runtime.onSuspendCanceled.addListener(
  callback: function,
)

Sent after onSuspend to indicate that the app won't be unloaded after all.

Parameters
  • callback

    function

    The callback parameter looks like: () => void

onUpdateAvailable

chrome.runtime.onUpdateAvailable.addListener(
  callback: function,
)

Fired when an update is available, but isn't installed immediately because the app is currently running. If you do nothing, the update will be installed the next time the background page gets unloaded, if you want it to be installed sooner you can explicitly call chrome.runtime.reload(). If your extension is using a persistent background page, the background page of course never gets unloaded, so unless you call chrome.runtime.reload() manually in response to this event the update will not get installed until the next time Chrome itself restarts. If no handlers are listening for this event, and your extension has a persistent background page, it behaves as if chrome.runtime.reload() is called in response to this event.

Parameters
  • callback

    function

    The callback parameter looks like: (details: object) => void

    • details

      object

      • version

        string

        可用更新的版本号。

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐