chrome.runtime

Beschrijving

Gebruik de chrome.runtime API om de service worker op te halen, details over het manifest te verkrijgen en te luisteren naar en te reageren op gebeurtenissen in de levenscyclus van de extensie. Je kunt deze API ook gebruiken om relatieve paden van URL's om te zetten naar volledig gekwalificeerde URL's.

Overzicht

De Runtime API biedt methoden ter ondersteuning van een aantal functionaliteiten die uw extensies kunnen gebruiken:

Berichtoverdracht
Je extensie kan communiceren met verschillende contexten binnen je extensie en ook met andere extensies met behulp van de volgende methoden en gebeurtenissen: connect() , onConnect , onConnectExternal , sendMessage() , onMessage en onMessageExternal . Daarnaast kan je extensie berichten doorgeven aan native applicaties op het apparaat van de gebruiker met behulp van connectNative() en sendNativeMessage() .
Toegang tot extensie- en platformmetadata
Met deze methoden kunt u verschillende specifieke metadata over de extensie en het platform ophalen. Methoden in deze categorie zijn onder andere getManifest() en getPlatformInfo() .
Het beheren van de levenscyclus en opties van extensies
Met deze eigenschappen kunt u bepaalde meta-bewerkingen op de extensie uitvoeren en de optiepagina weergeven. Methoden en gebeurtenissen in deze categorie zijn onder andere onInstalled , onStartup , openOptionsPage() , reload() , requestUpdateCheck() en setUninstallURL() .
Hulpprogramma's
Deze methoden bieden nuttige functies, zoals het omzetten van interne resource-representaties naar externe formaten. Methoden in deze categorie omvatten onder andere getURL() .
Hulpprogramma's in kioskmodus
Deze methoden zijn alleen beschikbaar op ChromeOS en zijn voornamelijk bedoeld ter ondersteuning van kioskimplementaties. Methoden in deze categorie zijn onder andere restart en restartAfterDelay .

Toestemmingen

De meeste methoden in de Runtime API vereisen geen toestemming, met uitzondering van sendNativeMessage en connectNative , waarvoor de nativeMessaging toestemming vereist is.

Manifest

Het volgende voorbeeld laat zien hoe u de nativeMessaging toestemming in het manifest kunt declareren:

manifest.json:

{
  "name": "My extension",
  ...
  "permissions": [
    "nativeMessaging"
  ],
  ...
}

Gebruiksvoorbeelden

Een afbeelding toevoegen aan een webpagina

Om toegang te krijgen tot een bestand dat op een ander domein wordt gehost, moet een webpagina de volledige URL van de bron opgeven (bijv. <img src="https://example.com/logo.png"> ). Hetzelfde geldt voor het opnemen van een extensiebestand op een webpagina. De twee verschillen zijn dat de bestanden van de extensie als webtoegankelijke bronnen beschikbaar moeten worden gesteld en dat content scripts doorgaans verantwoordelijk zijn voor het injecteren van extensiebestanden.

In dit voorbeeld voegt de extensie logo.png toe aan de pagina waarin het content-script wordt geïnjecteerd , door runtime.getURL() te gebruiken om een ​​volledig gekwalificeerde URL te creëren. Maar eerst moet de asset in het manifest worden gedeclareerd als een webtoegankelijke bron.

manifest.json:

{
  ...
  "web_accessible_resources": [
    {
      "resources": [ "logo.png" ],
      "matches": [ "https://*/*" ]
    }
  ],
  ...
}

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);
}

Verzend gegevens van de service worker naar een content script.

Het komt vaak voor dat de scripts voor de inhoud van een extensie gegevens nodig hebben die beheerd worden door een ander onderdeel van de extensie, zoals de service worker. Net zoals twee browservensters die dezelfde webpagina openen, hebben deze twee contexten geen directe toegang tot elkaars waarden. In plaats daarvan kan de extensie gebruikmaken van berichtuitwisseling om de communicatie tussen deze verschillende contexten te coördineren.

In dit voorbeeld heeft het contentscript gegevens nodig van de service worker van de extensie om de gebruikersinterface te initialiseren. Om deze gegevens te verkrijgen, stuurt het een get-user-data bericht naar de service worker, die vervolgens een kopie van de gebruikersinformatie terugstuurt.

content.js:

// 1. Send a message to the service worker requesting the user's data
chrome.runtime.sendMessage('get-user-data', (response) => {
  // 3. Got an asynchronous response with the data from the service worker
  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);
  }
});

Verzamel feedback over het verwijderen van bestanden.

Veel extensies gebruiken enquêtes na deïnstallatie om te begrijpen hoe de extensie de gebruikers beter van dienst kan zijn en de retentie kan verbeteren. Het volgende voorbeeld laat zien hoe je deze functionaliteit kunt toevoegen.

background.js:

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

Uitbreidingsvoorbeelden

Bekijk de demo Manifest V3 - Web Accessible Resources voor meer voorbeelden van de Runtime API.

Soorten

ContextFilter

Chrome 114+

Een filter om te matchen met bepaalde extensiecontexten. Overeenkomende contexten moeten aan alle opgegeven filters voldoen; elk filter dat niet is opgegeven, komt overeen met alle beschikbare contexten. Een filter van `{}` komt dus overeen met alle beschikbare contexten.

Eigenschappen

  • contextIds

    string[] optioneel

  • contextTypes

    ContextType [] optioneel

  • documentIds

    string[] optioneel

  • documentOrigins

    string[] optioneel

  • documentUrls

    string[] optioneel

  • frameIds

    nummer[] optioneel

  • incognito

    boolean optioneel

  • tabIds

    nummer[] optioneel

  • venster-ID's

    nummer[] optioneel

ContextType

Chrome 114+

Enum

"TAB"
Specificeert het contexttype als een tab.

"POP-UP"
Specificeert het contexttype als een extensie-pop-upvenster.

"ACHTERGROND"
Specificeert het contexttype als een service worker.

"OFFSCREEN_DOCUMENT"
Specificeert het contexttype als een document dat niet op het scherm zichtbaar is.

"ZIJPANEEL"
Specificeert het contexttype als een zijpaneel.

"ONTWIKKELAARSGEREEDSCHAPPEN"
Specificeert het contexttype als ontwikkelaarstools.

ExtensionContext

Chrome 114+

Een context die extensiecontent host.

Eigenschappen

  • contextId

    snaar

    Een unieke identificator voor deze context

  • contextType

    Het type context waar dit mee overeenkomt.

  • documentId

    string optioneel

    Een UUID voor het document dat aan deze context is gekoppeld, of 'undefined' als deze context niet in een document is opgeslagen.

  • documentOrigin

    string optioneel

    De herkomst van het document dat aan deze context is gekoppeld, of ongedefinieerd als de context niet in een document is opgenomen.

  • documentUrl

    string optioneel

    De URL van het document dat aan deze context is gekoppeld, of 'undefined' als de context niet in een document is opgeslagen.

  • frameId

    nummer

    De ID van het frame voor deze context, of -1 als deze context niet in een frame is gehost.

  • incognito

    booleaans

    Of de context verband houdt met een incognito-profiel.

  • tabId

    nummer

    De ID van het tabblad voor deze context, of -1 als deze context niet in een tabblad is gehost.

  • venster-ID

    nummer

    De ID van het venster voor deze context, of -1 als deze context niet in een venster wordt gehost.

MessageSender

Een object dat informatie bevat over de scriptcontext die een bericht of verzoek heeft verzonden.

Eigenschappen

  • documentId

    string optioneel

    Chrome 106+

    De UUID van het document waarmee de verbinding tot stand is gebracht.

  • documentLevenscyclus

    string optioneel

    Chrome 106+

    De levenscyclus waarin het document dat de verbinding opende zich bevond op het moment dat de poort werd aangemaakt. Houd er rekening mee dat de levenscyclusstatus van het document mogelijk is gewijzigd sinds de aanmaak van de poort.

  • frameId

    nummer optioneel

    Het frame dat de verbinding heeft geopend. 0 voor frames op het hoogste niveau, positief voor onderliggende frames. Dit wordt alleen ingesteld wanneer tab is geselecteerd.

  • id

    string optioneel

    De ID van de extensie die de verbinding heeft geopend, indien aanwezig.

  • nativeApplicatie

    string optioneel

    Chrome 74+

    De naam van de native applicatie die de verbinding heeft geopend, indien van toepassing.

  • oorsprong

    string optioneel

    Chrome 80+

    De oorsprong van de pagina of het frame dat de verbinding heeft geopend. Deze kan afwijken van de URL-eigenschap (bijvoorbeeld about:blank) of kan ondoorzichtig zijn (bijvoorbeeld sandboxed iframes). Dit is handig om te bepalen of de oorsprong betrouwbaar is als dit niet direct uit de URL af te leiden is.

  • tab

    Tab optioneel

    Het tabs.Tab dat de verbinding heeft geopend, indien aanwezig. Deze eigenschap is alleen aanwezig wanneer de verbinding is geopend vanuit een tabblad (inclusief inhoudsscripts) en alleen als de ontvanger een extensie is, en geen app.

  • tlsChannelId

    string optioneel

    De TLS-kanaal-ID van de pagina of het frame dat de verbinding heeft geopend, indien gevraagd door de extensie en indien beschikbaar.

  • URL

    string optioneel

    De URL van de pagina of het frame dat de verbinding heeft geopend. Als de afzender zich in een iframe bevindt, is dit de URL van het iframe en niet de URL van de pagina waarin het iframe zich bevindt.

OnInstalledReason

Chrome 44+

De reden waarom dit evenement wordt georganiseerd.

Enum

"installeren"
Specificeert de reden van de gebeurtenis als een installatie.

"update"
Specificeert de reden van de gebeurtenis als een extensie-update.

"chrome_update"
Geeft als reden voor de gebeurtenis aan dat het om een ​​Chrome-update gaat.

"shared_module_update"
Specificeert de reden van de gebeurtenis als een update van een gedeelde module.

OnRestartRequiredReason

Chrome 44+

De reden waarom de gebeurtenis wordt verzonden. 'app_update' wordt gebruikt wanneer een herstart nodig is omdat de applicatie is bijgewerkt naar een nieuwere versie. 'os_update' wordt gebruikt wanneer een herstart nodig is omdat de browser/het besturingssysteem is bijgewerkt naar een nieuwere versie. 'periodic' wordt gebruikt wanneer het systeem langer draait dan de toegestane uptime die is ingesteld in het bedrijfsbeleid.

Enum

"app_update"
Specificeert de reden van de gebeurtenis als een update van de app.

"os_update"
Specificeert de reden van de gebeurtenis als een update van het besturingssysteem.

"periodiek"
Specificeert de reden voor de gebeurtenis als een periodieke herstart van de app.

PlatformArch

Chrome 44+

De processorarchitectuur van de machine.

Enum

"arm"
Geeft aan dat de processorarchitectuur ARM is.

"arm64"
Geeft de processorarchitectuur aan als arm64.

"x86-32"
Geeft de processorarchitectuur aan als x86-32.

"x86-64"
Geeft de processorarchitectuur aan als x86-64.

"mips"
Specificeert de processorarchitectuur als mips.

"mips64"
Geeft de processorarchitectuur aan als mips64.

"riscv64"
Specificeert de processorarchitectuur als riscv64.

PlatformInfo

Een object dat informatie bevat over het huidige platform.

Eigenschappen

  • De processorarchitectuur van de machine.

  • nacl_arch

    PlatformNaclArch optioneel

    Niet meer bruikbaar sinds Chrome versie 149.

    Dit attribuut is verouderd na de volledige verwijdering van Native Client.

    De native clientarchitectuur. Deze kan op sommige platformen afwijken van de architectuur.

  • Het besturingssysteem waarop Chrome draait.

PlatformNaclArch

Chrome 44+ Niet meer ondersteund sinds Chrome 149

Deze enum is verouderd na de volledige verwijdering van Native Client.

De native clientarchitectuur. Deze kan op sommige platformen afwijken van de architectuur.

Enum

"arm"
Specificeert de native clientarchitectuur als arm.

"x86-32"
Specificeert de native clientarchitectuur als x86-32.

"x86-64"
Specificeert de native clientarchitectuur als x86-64.

"mips"
Specificeert de native clientarchitectuur als mips.

"mips64"
Specificeert de native clientarchitectuur als mips64.

PlatformOs

Chrome 44+

Het besturingssysteem waarop Chrome draait.

Enum

"mac"
Specificeert het MacOS-besturingssysteem.

"winnen"
Specificeert het Windows-besturingssysteem.

"android"
Specificeert het Android-besturingssysteem.

"kruisen"
Specificeert het Chrome-besturingssysteem.

"linux"
Specificeert het Linux-besturingssysteem.

"openbsd"
Specificeert het OpenBSD-besturingssysteem.

Port

Een object dat tweewegcommunicatie met andere pagina's mogelijk maakt. Zie Langdurige verbindingen voor meer informatie.

Eigenschappen

  • naam

    snaar

    De naam van de poort, zoals gespecificeerd in de aanroep van runtime.connect .

  • bijVerbinding verbreken

    Event<functionvoidvoid>

    Deze gebeurtenis wordt geactiveerd wanneer de poort wordt losgekoppeld van de andere kant(en). runtime.lastError kan worden ingesteld als de poort door een fout is losgekoppeld. Als de poort wordt gesloten via `disconnect` , wordt deze gebeurtenis alleen aan de andere kant geactiveerd. Deze gebeurtenis wordt maximaal één keer geactiveerd (zie ook Levensduur van de poort ).

    De functie onDisconnect.addListener ziet er als volgt uit:

    (callback: function) => {...}

    • terugbelverzoek

      functie

      De callback parameter ziet er als volgt uit:

      (port: Port) => void

  • onMessage

    Event<functionvoidvoid>

    Deze gebeurtenis wordt geactiveerd wanneer de postMessage-methode wordt aangeroepen door de andere kant van de poort.

    De functie onMessage.addListener ziet er als volgt uit:

    (callback: function) => {...}

    • terugbelverzoek

      functie

      De callback parameter ziet er als volgt uit:

      (message: any, port: Port) => void

  • afzender

    MessageSender (optioneel)

    Deze eigenschap is alleen aanwezig op poorten die worden doorgegeven aan onConnect / onConnectExternal / onConnectNative listeners.

  • ontkoppelen

    leegte

    Ontkoppel de poort onmiddellijk. Het aanroepen disconnect() op een poort die al is ontkoppeld, heeft geen effect. Wanneer een poort is ontkoppeld, worden er geen nieuwe gebeurtenissen meer naar deze poort verzonden.

    De functie disconnect ziet er als volgt uit:

    () => {...}

  • postMessage

    leegte

    Stuur een bericht naar de andere kant van de poort. Als de poort niet in gebruik is, wordt er een foutmelding gegenereerd.

    De postMessage functie ziet er als volgt uit:

    (message: any) => {...}

    • bericht

      elk

      Chrome 52+

      Het te verzenden bericht. Dit object moet in JSON-formaat te converteren zijn.

RequestUpdateCheckStatus

Chrome 44+

Resultaat van de updatecontrole.

Enum

"gewurgd"
Geeft aan dat de statuscontrole is vertraagd. Dit kan gebeuren na herhaalde controles binnen een korte tijdspanne.

"geen_update"
Geeft aan dat er geen updates beschikbaar zijn om te installeren.

"update_available"
Geeft aan dat er een beschikbare update is om te installeren.

Eigenschappen

id

De ID van de extensie/app.

Type

snaar

lastError

Deze eigenschap wordt gevuld met een foutmelding als het aanroepen van een API-functie mislukt; anders is deze niet gedefinieerd. Deze eigenschap is alleen gedefinieerd binnen de callback-functie. Als er een fout optreedt, maar runtime.lastError niet wordt aangeroepen binnen de callback, wordt een bericht naar de console gelogd met de naam van de API-functie die de fout heeft veroorzaakt. API-functies die promises retourneren, stellen deze eigenschap niet in.

Type

voorwerp

Eigenschappen

  • bericht

    string optioneel

    Details over de opgetreden fout.

Methoden

connect()

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

Pogingen om verbinding te maken met luisteraars binnen een extensie (zoals de achtergrondpagina) of met andere extensies/apps. Dit is handig voor contentscripts die verbinding maken met hun extensieprocessen, communicatie tussen apps/extensies en webberichten . Merk op dat dit geen verbinding maakt met luisteraars in een contentscript. Extensies kunnen verbinding maken met contentscripts die zijn ingesloten in tabbladen via tabs.connect .

Parameters

  • extensie-ID

    string optioneel

    De ID van de extensie waarmee verbinding moet worden gemaakt. Indien deze ID wordt weggelaten, wordt geprobeerd verbinding te maken met uw eigen extensie. Vereist bij het verzenden van berichten vanaf een webpagina voor webberichten .

  • verbindingsinfo

    object optioneel

    • includeTlsChannelId

      boolean optioneel

      Of de TLS-kanaal-ID wordt doorgegeven aan onConnectExternal voor processen die luisteren naar de verbindingsgebeurtenis.

    • naam

      string optioneel

      Wordt doorgegeven aan onConnect voor processen die luisteren naar de verbindingsgebeurtenis.

Retourneert

  • Poort waarlangs berichten kunnen worden verzonden en ontvangen. De onDisconnect- gebeurtenis van de poort wordt geactiveerd als de extensie niet bestaat.

connectNative()

chrome.runtime.connectNative(
  application: string,
)
: Port

Maakt verbinding met een native applicatie op de hostmachine. Deze methode vereist de machtiging "nativeMessaging" . Zie Native Messaging voor meer informatie.

Parameters

  • sollicitatie

    snaar

    De naam van de geregistreerde applicatie waarmee verbinding moet worden gemaakt.

Retourneert

  • Via deze poort kunnen berichten met de applicatie worden verzonden en ontvangen.

getBackgroundPage()

Promise Foreground only is verouderd sinds Chrome 133.
chrome.runtime.getBackgroundPage(
  callback?: function,
)
: Promise<Window | undefined>

Achtergrondpagina's bestaan ​​niet in MV3-extensies.

Haalt het JavaScript 'window'-object op voor de achtergrondpagina die binnen de huidige extensie/app wordt uitgevoerd. Als de achtergrondpagina een gebeurtenispagina is, zorgt het systeem ervoor dat deze wordt geladen voordat de callback wordt aangeroepen. Als er geen achtergrondpagina is, wordt een foutmelding gegenereerd.

Parameters

  • terugbelverzoek

    functie optioneel

    De callback parameter ziet er als volgt uit:

    (backgroundPage?: Window) => void

    • achtergrondpagina

      Venster optioneel

      Het JavaScript 'window'-object voor de achtergrondpagina.

Retourneert

  • Promise<Venster | niet gedefinieerd>

    Chrome 99+

    Promises worden alleen ondersteund voor Manifest V3 en later; voor andere platforms moeten callbacks worden gebruikt.

getManifest()

chrome.runtime.getManifest(): object

Geeft details over de app of extensie uit het manifestbestand terug. Het geretourneerde object is een serialisatie van het volledige manifestbestand .

Retourneert

  • voorwerp

    De manifestgegevens.

getPackageDirectoryEntry()

Belofte Alleen op de voorgrond
chrome.runtime.getPackageDirectoryEntry(
  callback?: function,
)
: Promise<DirectoryEntry>

Retourneert een DirectoryEntry voor de pakketdirectory.

Parameters

  • terugbelverzoek

    functie optioneel

    De callback parameter ziet er als volgt uit:

    (directoryEntry: DirectoryEntry) => void

    • directoryEntry

      DirectoryEntry

Retourneert

  • Promise<DirectoryEntry>

    Chrome 122+

    Promises worden alleen ondersteund voor Manifest V3 en later; voor andere platforms moeten callbacks worden gebruikt.

getPlatformInfo()

Belofte
chrome.runtime.getPlatformInfo(
  callback?: function,
)
: Promise<PlatformInfo>

Geeft informatie over het huidige platform.

Parameters

  • terugbelverzoek

    functie optioneel

    De callback parameter ziet er als volgt uit:

    (platformInfo: PlatformInfo) => void

Retourneert

  • Belofte< PlatformInfo >

    Chrome 99+

    Een belofte die wordt ingelost met informatie over het huidige platform.

    Promises worden alleen ondersteund voor Manifest V3 en later; voor andere platforms moeten callbacks worden gebruikt.

getURL()

chrome.runtime.getURL(
  path: string,
)
: string

Converteert een relatief pad binnen de installatiemap van een app/extensie naar een volledig gekwalificeerde URL.

Parameters

  • pad

    snaar

    Een pad naar een bron binnen een app/extensie, uitgedrukt ten opzichte van de installatiemap.

Retourneert

  • snaar

    De volledig gekwalificeerde URL naar de bron.

getVersion()

Chrome 143+
chrome.runtime.getVersion(): string

Retourneert de versie van de extensie zoals gedeclareerd in het manifest.

Retourneert

  • snaar

    De versie van de extensie.

openOptionsPage()

Belofte
chrome.runtime.openOptionsPage(
  callback?: function,
)
: Promise<void>

Open indien mogelijk de optiepagina van uw extensie.

Het precieze gedrag kan afhangen van de options_ui of options_page sleutel in uw manifest, of van wat Chrome op dat moment ondersteunt. De pagina kan bijvoorbeeld in een nieuw tabblad worden geopend, binnen `chrome://extensions`, binnen een app, of er kan simpelweg een geopende optiepagina worden geselecteerd. De pagina die de pagina aanroept, zal nooit opnieuw worden geladen.

Als uw extensie geen optiepagina declareert, of als Chrome er om een ​​andere reden niet in slaagt er een aan te maken, zal de callback lastError instellen.

Parameters

  • terugbelverzoek

    functie optioneel

    De callback parameter ziet er als volgt uit:

    () => void

Retourneert

  • Promise<void>

    Chrome 99+

    Promises worden alleen ondersteund voor Manifest V3 en later; voor andere platforms moeten callbacks worden gebruikt.

reload()

chrome.runtime.reload(): void

Herlaadt de app of extensie. Deze methode wordt niet ondersteund in de kioskmodus. Gebruik in de kioskmodus de methode chrome.runtime.restart().

requestUpdateCheck()

Belofte
chrome.runtime.requestUpdateCheck(
  callback?: function,
)
: Promise<object>

Verzoek om onmiddellijk te controleren op updates voor deze app/extensie.

Belangrijk : De meeste extensies/apps zouden deze methode niet moeten gebruiken, aangezien Chrome al elke paar uur automatisch controleert en je kunt luisteren naar de runtime.onUpdateAvailable -gebeurtenis zonder dat je requestUpdateCheck hoeft aan te roepen.

Deze methode is alleen geschikt voor zeer beperkte omstandigheden, bijvoorbeeld wanneer uw extensie communiceert met een backendservice en die service heeft vastgesteld dat de clientextensieversie sterk verouderd is en u de gebruiker wilt vragen om deze bij te werken. De meeste andere toepassingen van requestUpdateCheck, zoals het onvoorwaardelijk aanroepen ervan op basis van een herhalende timer, leiden waarschijnlijk alleen maar tot verspilling van client-, netwerk- en serverbronnen.

Opmerking: Wanneer deze functie met een callback wordt aangeroepen, retourneert deze in plaats van een object de twee eigenschappen als afzonderlijke argumenten die aan de callback worden doorgegeven.

Parameters

  • terugbelverzoek

    functie optioneel

    De callback parameter ziet er als volgt uit:

    (result: object) => void

    • resultaat

      voorwerp

      Chrome 109+

      Het RequestUpdateCheckResult-object bevat de status van de updatecontrole en eventuele details van het resultaat als er een update beschikbaar is.

      • Resultaat van de updatecontrole.

      • versie

        string optioneel

        Indien er een update beschikbaar is, wordt hier het versienummer van de beschikbare update weergegeven.

Retourneert

  • Promise<object>

    Chrome 109+

    Promises worden alleen ondersteund voor Manifest V3 en later; voor andere platforms moeten callbacks worden gebruikt.

restart()

chrome.runtime.restart(): void

Start het ChromeOS-apparaat opnieuw op wanneer de app in kioskmodus draait. Anders heeft het geen effect.

restartAfterDelay()

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

Start het ChromeOS-apparaat opnieuw op wanneer de app in kioskmodus draait na het opgegeven aantal seconden. Als deze functie opnieuw wordt aangeroepen voordat de tijd is verstreken, wordt de herstart uitgesteld. Als de functie wordt aangeroepen met een waarde van -1, wordt de herstart geannuleerd. In de niet-kioskmodus heeft deze functie geen effect. Deze functie mag alleen herhaaldelijk worden aangeroepen door de eerste extensie die deze API aanroept.

Parameters

  • seconden

    nummer

    De wachttijd in seconden voordat het apparaat opnieuw wordt opgestart, of -1 om een ​​geplande herstart te annuleren.

  • terugbelverzoek

    functie optioneel

    De callback parameter ziet er als volgt uit:

    () => void

Retourneert

  • Promise<void>

    Chrome 99+

    Een belofte die wordt ingelost wanneer een herstartverzoek succesvol opnieuw is ingepland.

    Promises worden alleen ondersteund voor Manifest V3 en later; voor andere platforms moeten callbacks worden gebruikt.

sendMessage()

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

Verzendt een enkel bericht naar gebeurtenislisteners binnen uw extensie of een andere extensie/app. Vergelijkbaar met runtime.connect , maar verzendt slechts één bericht, met een optioneel antwoord. Als u naar uw extensie verzendt, wordt de runtime.onMessage -gebeurtenis in elk frame van uw extensie geactiveerd (behalve in het frame van de afzender), of runtime.onMessageExternal als het een andere extensie betreft. Houd er rekening mee dat extensies met deze methode geen berichten naar contentscripts kunnen verzenden. Gebruik tabs.sendMessage om berichten naar contentscripts te verzenden.

Parameters

  • extensie-ID

    string optioneel

    De ID van de extensie waarnaar het bericht moet worden verzonden. Indien dit veld wordt weggelaten, wordt het bericht naar uw eigen extensie/app verzonden. Vereist bij het verzenden van berichten vanaf een webpagina voor webberichten .

  • bericht

    elk

    Het te verzenden bericht. Dit bericht moet een object zijn dat naar JSON kan worden geconverteerd.

  • opties

    object optioneel

    • includeTlsChannelId

      boolean optioneel

      Of de TLS-kanaal-ID wordt doorgegeven aan onMessageExternal voor processen die luisteren naar de verbindingsgebeurtenis.

  • terugbelverzoek

    functie optioneel

    Chrome 99+

    De callback parameter ziet er als volgt uit:

    (response: any) => void

    • antwoord

      elk

      Het JSON-antwoordobject dat door de handler van het bericht wordt verzonden. Als er een fout optreedt tijdens het verbinden met de extensie, wordt de callback zonder argumenten aangeroepen en wordt runtime.lastError ingesteld op het foutbericht.

Retourneert

  • Belofte<willekeurig>

    Chrome 99+

    In Chrome 99 werd ondersteuning voor promises toegevoegd aan extensiecontexten. Vanaf Chrome 118 zijn promises beschikbaar voor communicatie tussen een webpagina en een extensie.

    Promises worden alleen ondersteund voor Manifest V3 en later; voor andere platforms moeten callbacks worden gebruikt.

sendNativeMessage()

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

Een enkel bericht verzenden naar een native applicatie. Deze methode vereist de machtiging "nativeMessaging" .

Parameters

  • sollicitatie

    snaar

    De naam van de native berichtenhost of de doelgegevens.

  • bericht

    voorwerp

    Het bericht dat naar de native berichtenhost wordt verzonden.

  • terugbelverzoek

    functie optioneel

    Chrome 99+

    De callback parameter ziet er als volgt uit:

    (response: any) => void

    • antwoord

      elk

      Het antwoordbericht dat door de native berichtenhost wordt verzonden. Als er een fout optreedt tijdens het verbinden met de native berichtenhost, wordt de callback zonder argumenten aangeroepen en wordt runtime.lastError ingesteld op het foutbericht.

Retourneert

  • Belofte<willekeurig>

    Chrome 99+

    Promises worden alleen ondersteund voor Manifest V3 en later; voor andere platforms moeten callbacks worden gebruikt.

setUninstallURL()

Belofte
chrome.runtime.setUninstallURL(
  url: string,
  callback?: function,
)
: Promise<void>

Stelt de URL in die bezocht moet worden na deïnstallatie. Deze URL kan gebruikt worden voor het opschonen van servergegevens, het uitvoeren van analyses en het afnemen van enquêtes. Maximaal 1023 tekens.

Parameters

  • URL

    snaar

    De URL die geopend moet worden nadat de extensie is verwijderd. Deze URL moet een http: of https: schema hebben. Stel een lege tekenreeks in om geen nieuw tabblad te openen bij het verwijderen.

  • terugbelverzoek

    functie optioneel

    Chrome 45+

    De callback parameter ziet er als volgt uit:

    () => void

Retourneert

  • Promise<void>

    Chrome 99+

    Een belofte die wordt vervuld wanneer de URL voor het verwijderen is ingesteld. Als de opgegeven URL ongeldig is, wordt de belofte afgewezen.

    Promises worden alleen ondersteund voor Manifest V3 en later; voor andere platforms moeten callbacks worden gebruikt.

Evenementen

onBrowserUpdateAvailable

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

Gebruik alstublieft runtime.onRestartRequired .

Wordt geactiveerd wanneer er een Chrome-update beschikbaar is, maar deze wordt niet onmiddellijk geïnstalleerd omdat de browser opnieuw moet worden opgestart.

Parameters

  • terugbelverzoek

    functie

    De callback parameter ziet er als volgt uit:

    () => void

onConnect

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

Wordt geactiveerd wanneer een verbinding tot stand komt vanuit een extensieproces of een inhoudsscript (via runtime.connect ).

Parameters

  • terugbelverzoek

    functie

    De callback parameter ziet er als volgt uit:

    (port: Port) => void

onConnectExternal

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

Wordt geactiveerd wanneer een verbinding tot stand komt vanuit een andere extensie (via runtime.connect ) of vanuit een extern bereikbare website.

Parameters

  • terugbelverzoek

    functie

    De callback parameter ziet er als volgt uit:

    (port: Port) => void

onConnectNative

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

Deze gebeurtenis wordt geactiveerd wanneer een verbinding tot stand komt vanuit een native applicatie. Hiervoor is de machtiging "nativeMessaging" vereist. Deze functie wordt alleen ondersteund op Chrome OS.

Parameters

  • terugbelverzoek

    functie

    De callback parameter ziet er als volgt uit:

    (port: Port) => void

onEnabled

In behandeling
chrome.runtime.onEnabled.addListener(
  callback: function,
)

Wordt geactiveerd wanneer een extensie van een uitgeschakelde naar een ingeschakelde status overgaat.

Parameters

  • terugbelverzoek

    functie

    De callback parameter ziet er als volgt uit:

    () => void

onInstalled

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

Deze gebeurtenis wordt geactiveerd wanneer de extensie voor het eerst wordt geïnstalleerd, wanneer de extensie wordt bijgewerkt naar een nieuwe versie en wanneer Chrome wordt bijgewerkt naar een nieuwe versie.

Parameters

  • terugbelverzoek

    functie

    De callback parameter ziet er als volgt uit:

    (details: object) => void

    • details

      voorwerp

      • id

        string optioneel

        Geeft de ID aan van de geïmporteerde gedeelde module-extensie die is bijgewerkt. Deze is alleen aanwezig als 'reason' 'shared_module_update' is.

      • vorige versie

        string optioneel

        Geeft de vorige versie van de extensie aan, die zojuist is bijgewerkt. Dit is alleen aanwezig als 'reden' 'update' is.

      • De reden waarom dit evenement wordt georganiseerd.

onMessage

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

Wordt geactiveerd wanneer een bericht wordt verzonden vanuit runtime.sendMessage of tabs.sendMessage .

Parameters

  • terugbelverzoek

    functie

    De callback parameter ziet er als volgt uit:

    (message: any, sender: MessageSender, sendResponse: function) => boolean | Promise<any> | undefined

    • bericht

      elk

    • afzender
    • antwoord verzenden

      functie

      De parameter sendResponse ziet er als volgt uit:

      (response?: any) => void

      • antwoord

        eventuele optionele

        Het antwoord dat naar de afzender van het bericht wordt teruggestuurd.

    • retourneert

      boolean | Promise<any> | undefined

onMessageExternal

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

Wordt geactiveerd wanneer een bericht vanuit een andere extensie wordt verzonden (via runtime.sendMessage ). Kan niet worden gebruikt in een contentscript.

Parameters

  • terugbelverzoek

    functie

    De callback parameter ziet er als volgt uit:

    (message: any, sender: MessageSender, sendResponse: function) => boolean | Promise<any> | undefined

    • bericht

      elk

    • afzender
    • antwoord verzenden

      functie

      De parameter sendResponse ziet er als volgt uit:

      (response?: any) => void

      • antwoord

        eventuele optionele

        Het antwoord dat naar de afzender van het bericht wordt teruggestuurd.

    • retourneert

      boolean | Promise<any> | undefined

onRestartRequired

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

Deze gebeurtenis wordt geactiveerd wanneer een app of het apparaat waarop deze draait opnieuw moet worden opgestart. De app moet zo snel mogelijk alle vensters sluiten om de herstart mogelijk te maken. Als de app niets doet, wordt de herstart na een respijtperiode van 24 uur afgedwongen. Momenteel wordt deze gebeurtenis alleen geactiveerd voor Chrome OS-kiosk-apps.

Parameters

onStartup

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

Deze gebeurtenis wordt geactiveerd wanneer een profiel waarop deze extensie is geïnstalleerd, voor het eerst wordt opgestart. Deze gebeurtenis wordt niet geactiveerd wanneer een incognitoprofiel wordt gestart, zelfs niet als deze extensie in de 'gesplitste' incognitomodus werkt.

Parameters

  • terugbelverzoek

    functie

    De callback parameter ziet er als volgt uit:

    () => void

onSuspend

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

Deze gebeurtenis wordt naar de gebeurtenispagina verzonden vlak voordat deze wordt afgesloten. Dit geeft de extensie de mogelijkheid om wat opruimwerkzaamheden uit te voeren. Houd er rekening mee dat, aangezien de pagina wordt afgesloten, asynchrone bewerkingen die tijdens de afhandeling van deze gebeurtenis zijn gestart, niet gegarandeerd worden voltooid. Als er meer activiteit voor de gebeurtenispagina plaatsvindt voordat deze wordt afgesloten, wordt de gebeurtenis onSuspendCanceled verzonden en wordt de pagina niet afgesloten.

Parameters

  • terugbelverzoek

    functie

    De callback parameter ziet er als volgt uit:

    () => void

onSuspendCanceled

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

Verzonden na onSuspend om aan te geven dat de app toch niet wordt afgesloten.

Parameters

  • terugbelverzoek

    functie

    De callback parameter ziet er als volgt uit:

    () => void

onUpdateAvailable

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

Deze gebeurtenis wordt geactiveerd wanneer er een update beschikbaar is, maar deze wordt niet direct geïnstalleerd omdat de app momenteel actief is. Als u niets doet, wordt de update geïnstalleerd de volgende keer dat de achtergrondpagina wordt gesloten. Als u de update eerder wilt installeren, kunt u expliciet `chrome.runtime.reload()` aanroepen. Als uw extensie een permanente achtergrondpagina gebruikt, wordt deze pagina natuurlijk nooit gesloten. Tenzij u `chrome.runtime.reload()` handmatig aanroept als reactie op deze gebeurtenis, wordt de update pas geïnstalleerd wanneer Chrome zelf opnieuw wordt opgestart. Als er geen handlers naar deze gebeurtenis luisteren en uw extensie een permanente achtergrondpagina heeft, gedraagt ​​deze zich alsof `chrome.runtime.reload()` wordt aangeroepen als reactie op deze gebeurtenis.

Parameters

  • terugbelverzoek

    functie

    De callback parameter ziet er als volgt uit:

    (details: object) => void

    • details

      voorwerp

      • versie

        snaar

        Het versienummer van de beschikbare update.

,

Beschrijving

Gebruik de chrome.runtime API om de service worker op te halen, details over het manifest te verkrijgen en te luisteren naar en te reageren op gebeurtenissen in de levenscyclus van de extensie. Je kunt deze API ook gebruiken om relatieve paden van URL's om te zetten naar volledig gekwalificeerde URL's.

Overzicht

De Runtime API biedt methoden ter ondersteuning van een aantal functionaliteiten die uw extensies kunnen gebruiken:

Berichtoverdracht
Je extensie kan communiceren met verschillende contexten binnen je extensie en ook met andere extensies met behulp van de volgende methoden en gebeurtenissen: connect() , onConnect , onConnectExternal , sendMessage() , onMessage en onMessageExternal . Daarnaast kan je extensie berichten doorgeven aan native applicaties op het apparaat van de gebruiker met behulp van connectNative() en sendNativeMessage() .
Toegang tot extensie- en platformmetadata
Met deze methoden kunt u verschillende specifieke metadata over de extensie en het platform ophalen. Methoden in deze categorie zijn onder andere getManifest() en getPlatformInfo() .
Het beheren van de levenscyclus en opties van extensies
Met deze eigenschappen kunt u bepaalde meta-bewerkingen op de extensie uitvoeren en de optiepagina weergeven. Methoden en gebeurtenissen in deze categorie zijn onder andere onInstalled , onStartup , openOptionsPage() , reload() , requestUpdateCheck() en setUninstallURL() .
Hulpprogramma's
Deze methoden bieden nuttige functies, zoals het omzetten van interne resource-representaties naar externe formaten. Methoden in deze categorie omvatten onder andere getURL() .
Hulpprogramma's in kioskmodus
Deze methoden zijn alleen beschikbaar op ChromeOS en zijn voornamelijk bedoeld ter ondersteuning van kioskimplementaties. Methoden in deze categorie zijn onder andere restart en restartAfterDelay .

Toestemmingen

De meeste methoden in de Runtime API vereisen geen toestemming, met uitzondering van sendNativeMessage en connectNative , waarvoor de nativeMessaging toestemming vereist is.

Manifest

Het volgende voorbeeld laat zien hoe u de nativeMessaging toestemming in het manifest kunt declareren:

manifest.json:

{
  "name": "My extension",
  ...
  "permissions": [
    "nativeMessaging"
  ],
  ...
}

Gebruiksvoorbeelden

Een afbeelding toevoegen aan een webpagina

Om toegang te krijgen tot een bestand dat op een ander domein wordt gehost, moet een webpagina de volledige URL van de bron opgeven (bijv. <img src="https://example.com/logo.png"> ). Hetzelfde geldt voor het opnemen van een extensiebestand op een webpagina. De twee verschillen zijn dat de bestanden van de extensie als webtoegankelijke bronnen beschikbaar moeten worden gesteld en dat content scripts doorgaans verantwoordelijk zijn voor het injecteren van extensiebestanden.

In dit voorbeeld voegt de extensie logo.png toe aan de pagina waarin het content-script wordt geïnjecteerd , door runtime.getURL() te gebruiken om een ​​volledig gekwalificeerde URL te creëren. Maar eerst moet de asset in het manifest worden gedeclareerd als een webtoegankelijke bron.

manifest.json:

{
  ...
  "web_accessible_resources": [
    {
      "resources": [ "logo.png" ],
      "matches": [ "https://*/*" ]
    }
  ],
  ...
}

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);
}

Verzend gegevens van de service worker naar een content script.

Het komt vaak voor dat de scripts voor de inhoud van een extensie gegevens nodig hebben die beheerd worden door een ander onderdeel van de extensie, zoals de service worker. Net zoals twee browservensters die dezelfde webpagina openen, hebben deze twee contexten geen directe toegang tot elkaars waarden. In plaats daarvan kan de extensie gebruikmaken van berichtuitwisseling om de communicatie tussen deze verschillende contexten te coördineren.

In dit voorbeeld heeft het contentscript gegevens nodig van de service worker van de extensie om de gebruikersinterface te initialiseren. Om deze gegevens te verkrijgen, stuurt het een get-user-data bericht naar de service worker, die vervolgens een kopie van de gebruikersinformatie terugstuurt.

content.js:

// 1. Send a message to the service worker requesting the user's data
chrome.runtime.sendMessage('get-user-data', (response) => {
  // 3. Got an asynchronous response with the data from the service worker
  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);
  }
});

Verzamel feedback over het verwijderen van bestanden.

Veel extensies gebruiken enquêtes na deïnstallatie om te begrijpen hoe de extensie de gebruikers beter van dienst kan zijn en de retentie kan verbeteren. Het volgende voorbeeld laat zien hoe je deze functionaliteit kunt toevoegen.

background.js:

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

Uitbreidingsvoorbeelden

Bekijk de demo Manifest V3 - Web Accessible Resources voor meer voorbeelden van de Runtime API.

Soorten

ContextFilter

Chrome 114+

Een filter om te matchen met bepaalde extensiecontexten. Overeenkomende contexten moeten aan alle opgegeven filters voldoen; elk filter dat niet is opgegeven, komt overeen met alle beschikbare contexten. Een filter van `{}` komt dus overeen met alle beschikbare contexten.

Eigenschappen

  • contextIds

    string[] optioneel

  • contextTypes

    ContextType [] optioneel

  • documentIds

    string[] optioneel

  • documentOrigins

    string[] optioneel

  • documentUrls

    string[] optioneel

  • frameIds

    nummer[] optioneel

  • incognito

    boolean optioneel

  • tabIds

    nummer[] optioneel

  • venster-ID's

    nummer[] optioneel

ContextType

Chrome 114+

Enum

"TAB"
Specificeert het contexttype als een tab.

"POP-UP"
Specificeert het contexttype als een extensie-pop-upvenster.

"ACHTERGROND"
Specificeert het contexttype als een service worker.

"OFFSCREEN_DOCUMENT"
Specificeert het contexttype als een document dat niet op het scherm zichtbaar is.

"ZIJPANEEL"
Specificeert het contexttype als een zijpaneel.

"ONTWIKKELAARSGEREEDSCHAPPEN"
Specificeert het contexttype als ontwikkelaarstools.

ExtensionContext

Chrome 114+

Een context die extensiecontent host.

Eigenschappen

  • contextId

    snaar

    Een unieke identificator voor deze context

  • contextType

    Het type context waar dit mee overeenkomt.

  • documentId

    string optioneel

    Een UUID voor het document dat aan deze context is gekoppeld, of 'undefined' als deze context niet in een document is opgeslagen.

  • documentOrigin

    string optioneel

    De herkomst van het document dat aan deze context is gekoppeld, of ongedefinieerd als de context niet in een document is opgenomen.

  • documentUrl

    string optioneel

    De URL van het document dat aan deze context is gekoppeld, of 'undefined' als de context niet in een document is opgeslagen.

  • frameId

    nummer

    De ID van het frame voor deze context, of -1 als deze context niet in een frame is gehost.

  • incognito

    booleaans

    Of de context verband houdt met een incognito-profiel.

  • tabId

    nummer

    De ID van het tabblad voor deze context, of -1 als deze context niet in een tabblad is gehost.

  • venster-ID

    nummer

    De ID van het venster voor deze context, of -1 als deze context niet in een venster wordt gehost.

MessageSender

Een object dat informatie bevat over de scriptcontext die een bericht of verzoek heeft verzonden.

Eigenschappen

  • documentId

    string optioneel

    Chrome 106+

    De UUID van het document waarmee de verbinding tot stand is gebracht.

  • documentLevenscyclus

    string optioneel

    Chrome 106+

    De levenscyclus waarin het document dat de verbinding opende zich bevond op het moment dat de poort werd aangemaakt. Houd er rekening mee dat de levenscyclusstatus van het document mogelijk is gewijzigd sinds de aanmaak van de poort.

  • frameId

    nummer optioneel

    Het frame dat de verbinding heeft geopend. 0 voor frames op het hoogste niveau, positief voor onderliggende frames. Dit wordt alleen ingesteld wanneer tab is geselecteerd.

  • id

    string optioneel

    De ID van de extensie die de verbinding heeft geopend, indien aanwezig.

  • nativeApplicatie

    string optioneel

    Chrome 74+

    De naam van de native applicatie die de verbinding heeft geopend, indien van toepassing.

  • oorsprong

    string optioneel

    Chrome 80+

    De oorsprong van de pagina of het frame dat de verbinding heeft geopend. Deze kan afwijken van de URL-eigenschap (bijvoorbeeld about:blank) of kan ondoorzichtig zijn (bijvoorbeeld sandboxed iframes). Dit is handig om te bepalen of de oorsprong betrouwbaar is als dit niet direct uit de URL af te leiden is.

  • tab

    Tab optioneel

    Het tabs.Tab dat de verbinding heeft geopend, indien aanwezig. Deze eigenschap is alleen aanwezig wanneer de verbinding is geopend vanuit een tabblad (inclusief inhoudsscripts) en alleen als de ontvanger een extensie is, en geen app.

  • tlsChannelId

    string optioneel

    De TLS-kanaal-ID van de pagina of het frame dat de verbinding heeft geopend, indien gevraagd door de extensie en indien beschikbaar.

  • URL

    string optioneel

    De URL van de pagina of het frame dat de verbinding heeft geopend. Als de afzender zich in een iframe bevindt, is dit de URL van het iframe en niet de URL van de pagina waarin het iframe zich bevindt.

OnInstalledReason

Chrome 44+

De reden waarom dit evenement wordt georganiseerd.

Enum

"installeren"
Specificeert de reden van de gebeurtenis als een installatie.

"update"
Specificeert de reden van de gebeurtenis als een extensie-update.

"chrome_update"
Geeft als reden voor de gebeurtenis aan dat het om een ​​Chrome-update gaat.

"shared_module_update"
Specificeert de reden van de gebeurtenis als een update van een gedeelde module.

OnRestartRequiredReason

Chrome 44+

De reden waarom de gebeurtenis wordt verzonden. 'app_update' wordt gebruikt wanneer een herstart nodig is omdat de applicatie is bijgewerkt naar een nieuwere versie. 'os_update' wordt gebruikt wanneer een herstart nodig is omdat de browser/het besturingssysteem is bijgewerkt naar een nieuwere versie. 'periodic' wordt gebruikt wanneer het systeem langer draait dan de toegestane uptime die is ingesteld in het bedrijfsbeleid.

Enum

"app_update"
Specificeert de reden van de gebeurtenis als een update van de app.

"os_update"
Specificeert de reden van de gebeurtenis als een update van het besturingssysteem.

"periodiek"
Specificeert de reden voor de gebeurtenis als een periodieke herstart van de app.

PlatformArch

Chrome 44+

De processorarchitectuur van de machine.

Enum

"arm"
Geeft aan dat de processorarchitectuur ARM is.

"arm64"
Geeft de processorarchitectuur aan als arm64.

"x86-32"
Geeft de processorarchitectuur aan als x86-32.

"x86-64"
Geeft de processorarchitectuur aan als x86-64.

"mips"
Specificeert de processorarchitectuur als mips.

"mips64"
Geeft de processorarchitectuur aan als mips64.

"riscv64"
Specificeert de processorarchitectuur als riscv64.

PlatformInfo

Een object dat informatie bevat over het huidige platform.

Eigenschappen

  • De processorarchitectuur van de machine.

  • nacl_arch

    PlatformNaclArch optioneel

    Niet meer bruikbaar sinds Chrome versie 149.

    Dit attribuut is verouderd na de volledige verwijdering van Native Client.

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

  • The operating system Chrome is running on.

PlatformNaclArch

Chrome 44+ Deprecated since Chrome 149

This enum is deprecated following complete removal of Native Client.

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

Enum

"arm"
Specifies the native client architecture as arm.

"x86-32"
Specifies the native client architecture as x86-32.

"x86-64"
Specifies the native client architecture as x86-64.

"mips"
Specifies the native client architecture as mips.

"mips64"
Specifies the native client architecture as mips64.

PlatformOs

Chrome 44+

The operating system Chrome is running on.

Enum

"mac"
Specifies the MacOS operating system.

"winnen"
Specifies the Windows operating system.

"android"
Specifies the Android operating system.

"cros"
Specifies the Chrome operating system.

"linux"
Specifies the Linux operating system.

"openbsd"
Specifies the OpenBSD operating system.

Port

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

Eigenschappen

  • naam

    snaar

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

  • onDisconnect

    Event<functionvoidvoid>

    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) => {...}

    • terugbelverzoek

      functie

      The callback parameter looks like:

      (port: Port) => void

  • onMessage

    Event<functionvoidvoid>

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

    The onMessage.addListener function looks like:

    (callback: function) => {...}

    • terugbelverzoek

      functie

      The callback parameter looks like:

      (message: any, port: Port) => void

  • afzender

    MessageSender optional

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

  • ontkoppelen

    leegte

    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

    leegte

    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) => {...}

    • bericht

      elk

      Chrome 52+

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

RequestUpdateCheckStatus

Chrome 44+

Result of the update check.

Enum

"throttled"
Specifies that the status check has been throttled. This can occur after repeated checks within a short amount of time.

"no_update"
Specifies that there are no available updates to install.

"update_available"
Specifies that there is an available update to install.

Eigenschappen

id

The ID of the extension/app.

Type

snaar

lastError

Populated with an error message if calling an API function fails; otherwise undefined. This is only defined within the scope of that function's callback. If an error is produced, but runtime.lastError is not accessed within the callback, a message is logged to the console listing the API function that produced the error. API functions that return promises do not set this property.

Type

voorwerp

Eigenschappen

  • bericht

    string optional

    Details about the error which occurred.

Methoden

connect()

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

Attempts to connect listeners within an extension (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 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.

    • naam

      string optional

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

Retourneert

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

connectNative()

chrome.runtime.connectNative(
  application: string,
)
: Port

Connects to a native application in the host machine. This method requires the "nativeMessaging" permission. See Native Messaging for more information.

Parameters

  • sollicitatie

    snaar

    The name of the registered application to connect to.

Retourneert

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

getBackgroundPage()

Promise Foreground only is verouderd sinds Chrome 133.
chrome.runtime.getBackgroundPage(
  callback?: function,
)
: Promise<Window | undefined>

Background pages do not exist in MV3 extensions.

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

  • terugbelverzoek

    functie optioneel

    The callback parameter looks like:

    (backgroundPage?: Window) => void

    • achtergrondpagina

      Venster optioneel

      Het JavaScript 'window'-object voor de achtergrondpagina.

Retourneert

  • Promise<Window | undefined>

    Chrome 99+

    Promises worden alleen ondersteund voor Manifest V3 en later; voor andere platforms moeten callbacks worden gebruikt.

getManifest()

chrome.runtime.getManifest(): object

Returns details about the app or extension from the manifest. The object returned is a serialization of the full manifest file .

Retourneert

  • voorwerp

    The manifest details.

getPackageDirectoryEntry()

Belofte Alleen op de voorgrond
chrome.runtime.getPackageDirectoryEntry(
  callback?: function,
)
: Promise<DirectoryEntry>

Returns a DirectoryEntry for the package directory.

Parameters

  • terugbelverzoek

    functie optioneel

    The callback parameter looks like:

    (directoryEntry: DirectoryEntry) => void

    • directoryEntry

      DirectoryEntry

Retourneert

  • Promise<DirectoryEntry>

    Chrome 122+

    Promises worden alleen ondersteund voor Manifest V3 en later; voor andere platforms moeten callbacks worden gebruikt.

getPlatformInfo()

Belofte
chrome.runtime.getPlatformInfo(
  callback?: function,
)
: Promise<PlatformInfo>

Returns information about the current platform.

Parameters

  • terugbelverzoek

    functie optioneel

    The callback parameter looks like:

    (platformInfo: PlatformInfo) => void

Retourneert

  • Promise< PlatformInfo >

    Chrome 99+

    Promise that resolves with information about the current platform.

    Promises worden alleen ondersteund voor Manifest V3 en later; voor andere platforms moeten callbacks worden gebruikt.

getURL()

chrome.runtime.getURL(
  path: string,
)
: string

Converts a relative path within an app/extension install directory to a fully-qualified URL.

Parameters

  • pad

    snaar

    A path to a resource within an app/extension expressed relative to its install directory.

Retourneert

  • snaar

    The fully-qualified URL to the resource.

getVersion()

Chrome 143+
chrome.runtime.getVersion(): string

Returns the extension's version as declared in the manifest.

Retourneert

  • snaar

    The extension's version.

openOptionsPage()

Belofte
chrome.runtime.openOptionsPage(
  callback?: function,
)
: Promise<void>

Open your Extension's options page, if possible.

The precise behavior may depend on your manifest's options_ui or options_page key, or what Chrome happens to support at the time. For example, the page may be opened in a new tab, within chrome://extensions, within an App, or it may just focus an open options page. It will never cause the caller page to reload.

If your Extension does not declare an options page, or Chrome failed to create one for some other reason, the callback will set lastError .

Parameters

  • terugbelverzoek

    functie optioneel

    The callback parameter looks like:

    () => void

Retourneert

  • Promise<void>

    Chrome 99+

    Promises worden alleen ondersteund voor Manifest V3 en later; voor andere platforms moeten callbacks worden gebruikt.

reload()

chrome.runtime.reload(): void

Reloads the app or extension. This method is not supported in kiosk mode. For kiosk mode, use chrome.runtime.restart() method.

requestUpdateCheck()

Belofte
chrome.runtime.requestUpdateCheck(
  callback?: function,
)
: Promise<object>

Requests an immediate update check be done for this app/extension.

Important : Most extensions/apps should not use this method, since Chrome already does automatic checks every few hours, and you can listen for the runtime.onUpdateAvailable event without needing to call requestUpdateCheck.

This method is only appropriate to call in very limited circumstances, such as if your extension talks to a backend service, and the backend service has determined that the client extension version is very far out of date and you'd like to prompt a user to update. Most other uses of requestUpdateCheck, such as calling it unconditionally based on a repeating timer, probably only serve to waste client, network, and server resources.

Note: When called with a callback, instead of returning an object this function will return the two properties as separate arguments passed to the callback.

Parameters

  • terugbelverzoek

    functie optioneel

    The callback parameter looks like:

    (result: object) => void

    • resultaat

      voorwerp

      Chrome 109+

      Het RequestUpdateCheckResult-object bevat de status van de updatecontrole en eventuele details van het resultaat als er een update beschikbaar is.

      • Result of the update check.

      • versie

        string optional

        Indien er een update beschikbaar is, wordt hier het versienummer van de beschikbare update weergegeven.

Retourneert

  • Promise<object>

    Chrome 109+

    Promises worden alleen ondersteund voor Manifest V3 en later; voor andere platforms moeten callbacks worden gebruikt.

restart()

chrome.runtime.restart(): void

Restart the ChromeOS device when the app runs in kiosk mode. Otherwise, it's no-op.

restartAfterDelay()

PromiseChrome 53+
chrome.runtime.restartAfterDelay(
  seconds: number,
  callback?: function,
)
: Promise<void>

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

  • seconden

    nummer

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

  • terugbelverzoek

    functie optioneel

    The callback parameter looks like:

    () => void

Retourneert

  • Promise<void>

    Chrome 99+

    Promise that resolves when a restart request was successfully rescheduled.

    Promises worden alleen ondersteund voor Manifest V3 en later; voor andere platforms moeten callbacks worden gebruikt.

sendMessage()

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

Sends a single message to event listeners within your extension 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 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 .

  • bericht

    elk

    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.

  • terugbelverzoek

    functie optioneel

    Chrome 99+

    The callback parameter looks like:

    (response: any) => void

    • antwoord

      elk

      Het JSON-antwoordobject dat door de handler van het bericht wordt verzonden. Als er een fout optreedt tijdens het verbinden met de extensie, wordt de callback zonder argumenten aangeroepen en wordt runtime.lastError ingesteld op het foutbericht.

Retourneert

  • Promise<any>

    Chrome 99+

    Promise support was added for extension contexts in Chrome 99. When communicating from a web page to an extension, promises are available from Chrome 118.

    Promises worden alleen ondersteund voor Manifest V3 en later; voor andere platforms moeten callbacks worden gebruikt.

sendNativeMessage()

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

Send a single message to a native application. This method requires the "nativeMessaging" permission.

Parameters

  • sollicitatie

    snaar

    The name of the native messaging host, or target details.

  • bericht

    voorwerp

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

  • terugbelverzoek

    functie optioneel

    Chrome 99+

    The callback parameter looks like:

    (response: any) => void

    • antwoord

      elk

      Het antwoordbericht dat door de native berichtenhost wordt verzonden. Als er een fout optreedt tijdens het verbinden met de native berichtenhost, wordt de callback zonder argumenten aangeroepen en wordt runtime.lastError ingesteld op het foutbericht.

Retourneert

  • Promise<any>

    Chrome 99+

    Promises worden alleen ondersteund voor Manifest V3 en later; voor andere platforms moeten callbacks worden gebruikt.

setUninstallURL()

Belofte
chrome.runtime.setUninstallURL(
  url: string,
  callback?: function,
)
: Promise<void>

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

Parameters

  • URL

    snaar

    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.

  • terugbelverzoek

    functie optioneel

    Chrome 45+

    The callback parameter looks like:

    () => void

Retourneert

  • Promise<void>

    Chrome 99+

    Promise that resolves when the uninstall URL is set. If the given URL is invalid, the promise will be rejected.

    Promises worden alleen ondersteund voor Manifest V3 en later; voor andere platforms moeten callbacks worden gebruikt.

Evenementen

onBrowserUpdateAvailable

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

Please use runtime.onRestartRequired .

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

Parameters

  • terugbelverzoek

    functie

    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

  • terugbelverzoek

    functie

    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 ), or from an externally connectable web site.

Parameters

  • terugbelverzoek

    functie

    The callback parameter looks like:

    (port: Port) => void

onConnectNative

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

Fired when a connection is made from a native application. This event requires the "nativeMessaging" permission. It is only supported on Chrome OS.

Parameters

  • terugbelverzoek

    functie

    The callback parameter looks like:

    (port: Port) => void

onEnabled

In behandeling
chrome.runtime.onEnabled.addListener(
  callback: function,
)

Wordt geactiveerd wanneer een extensie van een uitgeschakelde naar een ingeschakelde status overgaat.

Parameters

  • terugbelverzoek

    functie

    The callback parameter looks like:

    () => 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

  • terugbelverzoek

    functie

    The callback parameter looks like:

    (details: object) => void

    • details

      voorwerp

      • 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 runtime.sendMessage or tabs.sendMessage .

Parameters

  • terugbelverzoek

    functie

    The callback parameter looks like:

    (message: any, sender: MessageSender, sendResponse: function) => boolean | Promise<any> | undefined

    • bericht

      elk

    • afzender
    • sendResponse

      functie

      The sendResponse parameter looks like:

      (response?: any) => void

      • antwoord

        any optional

        The response to return to the message sender.

    • retourneert

      boolean | Promise<any> | undefined

onMessageExternal

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

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

Parameters

  • terugbelverzoek

    functie

    The callback parameter looks like:

    (message: any, sender: MessageSender, sendResponse: function) => boolean | Promise<any> | undefined

    • bericht

      elk

    • afzender
    • sendResponse

      functie

      The sendResponse parameter looks like:

      (response?: any) => void

      • antwoord

        any optional

        The response to return to the message sender.

    • retourneert

      boolean | Promise<any> | 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

  • terugbelverzoek

    functie

    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

  • terugbelverzoek

    functie

    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

  • terugbelverzoek

    functie

    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

  • terugbelverzoek

    functie

    The callback parameter looks like:

    (details: object) => void

    • details

      voorwerp

      • versie

        snaar

        The version number of the available update.

,

Beschrijving

Use the chrome.runtime API to retrieve the service worker, return details about the manifest, and listen for and respond to events in the extension lifecycle. You can also use this API to convert the relative path of URLs to fully-qualified URLs.

Overzicht

De Runtime API biedt methoden ter ondersteuning van een aantal functionaliteiten die uw extensies kunnen gebruiken:

Message passing
Your extension can communicate with different contexts within your extension and also with other extensions using these methods and events: connect() , onConnect , onConnectExternal , sendMessage() , onMessage and onMessageExternal . In addition, your extension can pass messages to native applications on the user's device using connectNative() and sendNativeMessage() .
Accessing extension and platform metadata
These methods let you retrieve several specific pieces of metadata about the extension and the platform. Methods in this category include getManifest() , and getPlatformInfo() .
Managing extension lifecycle and options
These properties let you perform some meta-operations on the extension, and display the options page. Methods and events in this category include onInstalled , onStartup , openOptionsPage() , reload() , requestUpdateCheck() , and setUninstallURL() .
Helper utilities
These methods provide utility such as the conversion of internal resource representations to external formats. Methods in this category include getURL() .
Kiosk mode utilities
Deze methoden zijn alleen beschikbaar op ChromeOS en zijn voornamelijk bedoeld ter ondersteuning van kioskimplementaties. Methoden in deze categorie zijn onder andere restart en restartAfterDelay .

Toestemmingen

De meeste methoden in de Runtime API vereisen geen toestemming, met uitzondering van sendNativeMessage en connectNative , waarvoor de nativeMessaging toestemming vereist is.

Manifest

Het volgende voorbeeld laat zien hoe u de nativeMessaging toestemming in het manifest kunt declareren:

manifest.json:

{
  "name": "My extension",
  ...
  "permissions": [
    "nativeMessaging"
  ],
  ...
}

Gebruiksvoorbeelden

Add an image to a web page

For a web page to access an asset hosted on another domain, it must specify the resource's full URL (eg <img src="https://example.com/logo.png"> ). The same is true to include an extension asset on a web page. The two differences are that the extension's assets must be exposed as web accessible resources and that typically content scripts are responsible for injecting extension assets.

In this example, the extension will add logo.png to the page that the content script is being injected into by using runtime.getURL() to create a fully-qualified URL. But first, the asset must be declared as a web accessible resource in the manifest.

manifest.json:

{
  ...
  "web_accessible_resources": [
    {
      "resources": [ "logo.png" ],
      "matches": [ "https://*/*" ]
    }
  ],
  ...
}

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);
}

Verzend gegevens van de service worker naar een content script.

Het komt vaak voor dat de scripts voor de inhoud van een extensie gegevens nodig hebben die beheerd worden door een ander onderdeel van de extensie, zoals de service worker. Net zoals twee browservensters die dezelfde webpagina openen, hebben deze twee contexten geen directe toegang tot elkaars waarden. In plaats daarvan kan de extensie gebruikmaken van berichtuitwisseling om de communicatie tussen deze verschillende contexten te coördineren.

In dit voorbeeld heeft het contentscript gegevens nodig van de service worker van de extensie om de gebruikersinterface te initialiseren. Om deze gegevens te verkrijgen, stuurt het een get-user-data bericht naar de service worker, die vervolgens een kopie van de gebruikersinformatie terugstuurt.

content.js:

// 1. Send a message to the service worker requesting the user's data
chrome.runtime.sendMessage('get-user-data', (response) => {
  // 3. Got an asynchronous response with the data from the service worker
  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);
  }
});

Gather feedback on uninstall

Many extensions use post-uninstall surveys to understand how the extension could better serve its users and improve retention. The following example shows how to add this functionality.

background.js:

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

Uitbreidingsvoorbeelden

See the Manifest V3 - Web Accessible Resources demo for more Runtime API examples.

Soorten

ContextFilter

Chrome 114+

A filter to match against certain extension contexts. Matching contexts must match all specified filters; any filter that is not specified matches all available contexts. Thus, a filter of `{}` will match all available contexts.

Eigenschappen

  • contextIds

    string[] optional

  • contextTypes

    ContextType [] optional

  • documentIds

    string[] optional

  • documentOrigins

    string[] optional

  • documentUrls

    string[] optional

  • frameIds

    number[] optional

  • incognito

    boolean optional

  • tabIds

    number[] optional

  • windowIds

    number[] optional

ContextType

Chrome 114+

Enum

"TAB"
Specifies the context type as a tab

"POPUP"
Specifies the context type as an extension popup window

"ACHTERGROND"
Specifies the context type as a service worker.

"OFFSCREEN_DOCUMENT"
Specifies the context type as an offscreen document.

"SIDE_PANEL"
Specifies the context type as a side panel.

"DEVELOPER_TOOLS"
Specifies the context type as developer tools.

ExtensionContext

Chrome 114+

A context hosting extension content.

Eigenschappen

  • contextId

    snaar

    A unique identifier for this context

  • contextType

    The type of context this corresponds to.

  • documentId

    string optional

    A UUID for the document associated with this context, or undefined if this context is hosted not in a document.

  • documentOrigin

    string optional

    The origin of the document associated with this context, or undefined if the context is not hosted in a document.

  • documentUrl

    string optional

    The URL of the document associated with this context, or undefined if the context is not hosted in a document.

  • frameId

    nummer

    The ID of the frame for this context, or -1 if this context is not hosted in a frame.

  • incognito

    booleaans

    Whether the context is associated with an incognito profile.

  • tabId

    nummer

    The ID of the tab for this context, or -1 if this context is not hosted in a tab.

  • windowId

    nummer

    The ID of the window for this context, or -1 if this context is not hosted in a window.

MessageSender

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

Eigenschappen

  • documentId

    string optional

    Chrome 106+

    A UUID of the document that opened the connection.

  • documentLifecycle

    string optional

    Chrome 106+

    The lifecycle the document that opened the connection is in at the time the port was created. Note that the lifecycle state of the document may have changed since port creation.

  • 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 that opened the connection, if any.

  • nativeApplication

    string optional

    Chrome 74+

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

  • oorsprong

    string optional

    Chrome 80+

    The origin of the page or frame that opened the connection. It can vary from the url property (eg, about:blank) or can be opaque (eg, 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, 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.

Enum

"installeren"
Specifies the event reason as an installation.

"update"
Specifies the event reason as an extension update.

"chrome_update"
Specifies the event reason as a Chrome update.

"shared_module_update"
Specifies the event reason as an update to a shared module.

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.

Enum

"app_update"
Specifies the event reason as an update to the app.

"os_update"
Specifies the event reason as an update to the operating system.

"periodic"
Specifies the event reason as a periodic restart of the app.

PlatformArch

Chrome 44+

The machine's processor architecture.

Enum

"arm"
Specifies the processer architecture as arm.

"arm64"
Specifies the processer architecture as arm64.

"x86-32"
Specifies the processer architecture as x86-32.

"x86-64"
Specifies the processer architecture as x86-64.

"mips"
Specifies the processer architecture as mips.

"mips64"
Specifies the processer architecture as mips64.

"riscv64"
Specifies the processer architecture as riscv64.

PlatformInfo

An object containing information about the current platform.

Eigenschappen

  • The machine's processor architecture.

  • nacl_arch
    Deprecated since Chrome 149

    This attribute is deprecated following complete removal of Native Client.

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

  • The operating system Chrome is running on.

PlatformNaclArch

Chrome 44+ Deprecated since Chrome 149

This enum is deprecated following complete removal of Native Client.

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

Enum

"arm"
Specifies the native client architecture as arm.

"x86-32"
Specifies the native client architecture as x86-32.

"x86-64"
Specifies the native client architecture as x86-64.

"mips"
Specifies the native client architecture as mips.

"mips64"
Specifies the native client architecture as mips64.

PlatformOs

Chrome 44+

The operating system Chrome is running on.

Enum

"mac"
Specifies the MacOS operating system.

"winnen"
Specifies the Windows operating system.

"android"
Specifies the Android operating system.

"cros"
Specifies the Chrome operating system.

"linux"
Specifies the Linux operating system.

"openbsd"
Specifies the OpenBSD operating system.

Port

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

Eigenschappen

  • naam

    snaar

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

  • onDisconnect

    Event<functionvoidvoid>

    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) => {...}

    • terugbelverzoek

      functie

      The callback parameter looks like:

      (port: Port) => void

  • onMessage

    Event<functionvoidvoid>

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

    The onMessage.addListener function looks like:

    (callback: function) => {...}

    • terugbelverzoek

      functie

      The callback parameter looks like:

      (message: any, port: Port) => void

  • afzender

    MessageSender optional

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

  • ontkoppelen

    leegte

    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

    leegte

    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) => {...}

    • bericht

      elk

      Chrome 52+

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

RequestUpdateCheckStatus

Chrome 44+

Result of the update check.

Enum

"throttled"
Specifies that the status check has been throttled. This can occur after repeated checks within a short amount of time.

"no_update"
Specifies that there are no available updates to install.

"update_available"
Specifies that there is an available update to install.

Eigenschappen

id

The ID of the extension/app.

Type

snaar

lastError

Populated with an error message if calling an API function fails; otherwise undefined. This is only defined within the scope of that function's callback. If an error is produced, but runtime.lastError is not accessed within the callback, a message is logged to the console listing the API function that produced the error. API functions that return promises do not set this property.

Type

voorwerp

Eigenschappen

  • bericht

    string optional

    Details about the error which occurred.

Methoden

connect()

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

Attempts to connect listeners within an extension (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 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.

    • naam

      string optional

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

Retourneert

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

connectNative()

chrome.runtime.connectNative(
  application: string,
)
: Port

Connects to a native application in the host machine. This method requires the "nativeMessaging" permission. See Native Messaging for more information.

Parameters

  • sollicitatie

    snaar

    The name of the registered application to connect to.

Retourneert

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

getBackgroundPage()

Promise Foreground only is verouderd sinds Chrome 133.
chrome.runtime.getBackgroundPage(
  callback?: function,
)
: Promise<Window | undefined>

Background pages do not exist in MV3 extensions.

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

  • terugbelverzoek

    functie optioneel

    The callback parameter looks like:

    (backgroundPage?: Window) => void

    • achtergrondpagina

      Venster optioneel

      Het JavaScript 'window'-object voor de achtergrondpagina.

Retourneert

  • Promise<Window | undefined>

    Chrome 99+

    Promises worden alleen ondersteund voor Manifest V3 en later; voor andere platforms moeten callbacks worden gebruikt.

getManifest()

chrome.runtime.getManifest(): object

Returns details about the app or extension from the manifest. The object returned is a serialization of the full manifest file .

Retourneert

  • voorwerp

    The manifest details.

getPackageDirectoryEntry()

Belofte Alleen op de voorgrond
chrome.runtime.getPackageDirectoryEntry(
  callback?: function,
)
: Promise<DirectoryEntry>

Returns a DirectoryEntry for the package directory.

Parameters

  • terugbelverzoek

    functie optioneel

    The callback parameter looks like:

    (directoryEntry: DirectoryEntry) => void

    • directoryEntry

      DirectoryEntry

Retourneert

  • Promise<DirectoryEntry>

    Chrome 122+

    Promises worden alleen ondersteund voor Manifest V3 en later; voor andere platforms moeten callbacks worden gebruikt.

getPlatformInfo()

Belofte
chrome.runtime.getPlatformInfo(
  callback?: function,
)
: Promise<PlatformInfo>

Returns information about the current platform.

Parameters

  • terugbelverzoek

    functie optioneel

    The callback parameter looks like:

    (platformInfo: PlatformInfo) => void

Retourneert

  • Promise< PlatformInfo >

    Chrome 99+

    Promise that resolves with information about the current platform.

    Promises worden alleen ondersteund voor Manifest V3 en later; voor andere platforms moeten callbacks worden gebruikt.

getURL()

chrome.runtime.getURL(
  path: string,
)
: string

Converts a relative path within an app/extension install directory to a fully-qualified URL.

Parameters

  • pad

    snaar

    A path to a resource within an app/extension expressed relative to its install directory.

Retourneert

  • snaar

    The fully-qualified URL to the resource.

getVersion()

Chrome 143+
chrome.runtime.getVersion(): string

Returns the extension's version as declared in the manifest.

Retourneert

  • snaar

    The extension's version.

openOptionsPage()

Belofte
chrome.runtime.openOptionsPage(
  callback?: function,
)
: Promise<void>

Open your Extension's options page, if possible.

The precise behavior may depend on your manifest's options_ui or options_page key, or what Chrome happens to support at the time. For example, the page may be opened in a new tab, within chrome://extensions, within an App, or it may just focus an open options page. It will never cause the caller page to reload.

If your Extension does not declare an options page, or Chrome failed to create one for some other reason, the callback will set lastError .

Parameters

  • terugbelverzoek

    functie optioneel

    The callback parameter looks like:

    () => void

Retourneert

  • Promise<void>

    Chrome 99+

    Promises worden alleen ondersteund voor Manifest V3 en later; voor andere platforms moeten callbacks worden gebruikt.

reload()

chrome.runtime.reload(): void

Reloads the app or extension. This method is not supported in kiosk mode. For kiosk mode, use chrome.runtime.restart() method.

requestUpdateCheck()

Belofte
chrome.runtime.requestUpdateCheck(
  callback?: function,
)
: Promise<object>

Requests an immediate update check be done for this app/extension.

Important : Most extensions/apps should not use this method, since Chrome already does automatic checks every few hours, and you can listen for the runtime.onUpdateAvailable event without needing to call requestUpdateCheck.

This method is only appropriate to call in very limited circumstances, such as if your extension talks to a backend service, and the backend service has determined that the client extension version is very far out of date and you'd like to prompt a user to update. Most other uses of requestUpdateCheck, such as calling it unconditionally based on a repeating timer, probably only serve to waste client, network, and server resources.

Note: When called with a callback, instead of returning an object this function will return the two properties as separate arguments passed to the callback.

Parameters

  • terugbelverzoek

    functie optioneel

    The callback parameter looks like:

    (result: object) => void

    • resultaat

      voorwerp

      Chrome 109+

      Het RequestUpdateCheckResult-object bevat de status van de updatecontrole en eventuele details van het resultaat als er een update beschikbaar is.

      • Result of the update check.

      • versie

        string optional

        Indien er een update beschikbaar is, wordt hier het versienummer van de beschikbare update weergegeven.

Retourneert

  • Promise<object>

    Chrome 109+

    Promises worden alleen ondersteund voor Manifest V3 en later; voor andere platforms moeten callbacks worden gebruikt.

restart()

chrome.runtime.restart(): void

Restart the ChromeOS device when the app runs in kiosk mode. Otherwise, it's no-op.

restartAfterDelay()

PromiseChrome 53+
chrome.runtime.restartAfterDelay(
  seconds: number,
  callback?: function,
)
: Promise<void>

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

  • seconden

    nummer

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

  • terugbelverzoek

    functie optioneel

    The callback parameter looks like:

    () => void

Retourneert

  • Promise<void>

    Chrome 99+

    Promise that resolves when a restart request was successfully rescheduled.

    Promises worden alleen ondersteund voor Manifest V3 en later; voor andere platforms moeten callbacks worden gebruikt.

sendMessage()

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

Sends a single message to event listeners within your extension 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 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 .

  • bericht

    elk

    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.

  • terugbelverzoek

    functie optioneel

    Chrome 99+

    The callback parameter looks like:

    (response: any) => void

    • antwoord

      elk

      Het JSON-antwoordobject dat door de handler van het bericht wordt verzonden. Als er een fout optreedt tijdens het verbinden met de extensie, wordt de callback zonder argumenten aangeroepen en wordt runtime.lastError ingesteld op het foutbericht.

Retourneert

  • Promise<any>

    Chrome 99+

    Promise support was added for extension contexts in Chrome 99. When communicating from a web page to an extension, promises are available from Chrome 118.

    Promises worden alleen ondersteund voor Manifest V3 en later; voor andere platforms moeten callbacks worden gebruikt.

sendNativeMessage()

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

Send a single message to a native application. This method requires the "nativeMessaging" permission.

Parameters

  • sollicitatie

    snaar

    The name of the native messaging host, or target details.

  • bericht

    voorwerp

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

  • terugbelverzoek

    functie optioneel

    Chrome 99+

    The callback parameter looks like:

    (response: any) => void

    • antwoord

      elk

      Het antwoordbericht dat door de native berichtenhost wordt verzonden. Als er een fout optreedt tijdens het verbinden met de native berichtenhost, wordt de callback zonder argumenten aangeroepen en wordt runtime.lastError ingesteld op het foutbericht.

Retourneert

  • Promise<any>

    Chrome 99+

    Promises worden alleen ondersteund voor Manifest V3 en later; voor andere platforms moeten callbacks worden gebruikt.

setUninstallURL()

Belofte
chrome.runtime.setUninstallURL(
  url: string,
  callback?: function,
)
: Promise<void>

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

Parameters

  • URL

    snaar

    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.

  • terugbelverzoek

    functie optioneel

    Chrome 45+

    The callback parameter looks like:

    () => void

Retourneert

  • Promise<void>

    Chrome 99+

    Promise that resolves when the uninstall URL is set. If the given URL is invalid, the promise will be rejected.

    Promises worden alleen ondersteund voor Manifest V3 en later; voor andere platforms moeten callbacks worden gebruikt.

Evenementen

onBrowserUpdateAvailable

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

Please use runtime.onRestartRequired .

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

Parameters

  • terugbelverzoek

    functie

    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

  • terugbelverzoek

    functie

    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 ), or from an externally connectable web site.

Parameters

  • terugbelverzoek

    functie

    The callback parameter looks like:

    (port: Port) => void

onConnectNative

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

Fired when a connection is made from a native application. This event requires the "nativeMessaging" permission. It is only supported on Chrome OS.

Parameters

  • terugbelverzoek

    functie

    The callback parameter looks like:

    (port: Port) => void

onEnabled

In behandeling
chrome.runtime.onEnabled.addListener(
  callback: function,
)

Wordt geactiveerd wanneer een extensie van een uitgeschakelde naar een ingeschakelde status overgaat.

Parameters

  • terugbelverzoek

    functie

    The callback parameter looks like:

    () => 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

  • terugbelverzoek

    functie

    The callback parameter looks like:

    (details: object) => void

    • details

      voorwerp

      • 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 runtime.sendMessage or tabs.sendMessage .

Parameters

  • terugbelverzoek

    functie

    The callback parameter looks like:

    (message: any, sender: MessageSender, sendResponse: function) => boolean | Promise<any> | undefined

    • bericht

      elk

    • afzender
    • sendResponse

      functie

      The sendResponse parameter looks like:

      (response?: any) => void

      • antwoord

        any optional

        The response to return to the message sender.

    • retourneert

      boolean | Promise<any> | undefined

onMessageExternal

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

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

Parameters

  • terugbelverzoek

    functie

    The callback parameter looks like:

    (message: any, sender: MessageSender, sendResponse: function) => boolean | Promise<any> | undefined

    • bericht

      elk

    • afzender
    • sendResponse

      functie

      The sendResponse parameter looks like:

      (response?: any) => void

      • antwoord

        any optional

        The response to return to the message sender.

    • retourneert

      boolean | Promise<any> | 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

  • terugbelverzoek

    functie

    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

  • terugbelverzoek

    functie

    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

  • terugbelverzoek

    functie

    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

  • terugbelverzoek

    functie

    The callback parameter looks like:

    (details: object) => void

    • details

      voorwerp

      • versie

        snaar

        The version number of the available update.