Google chrome events javascript

chrome.runtime

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

  • Permissions
  • Manifest
  • Use cases
    • Add an image to a web page
    • Send data from the service worker to a content script
    • Gather feedback on uninstall
    • ContextFilter
    • ContextType
    • ExtensionContext
    • MessageSender
    • OnInstalledReason
    • OnRestartRequiredReason
    • PlatformArch
    • PlatformInfo
    • PlatformNaclArch
    • PlatformOs
    • Port
    • RequestUpdateCheckStatus
    • id
    • lastError
    • connect
    • connectNative
    • getBackgroundPage
    • getContexts
    • getManifest
    • getPackageDirectoryEntry
    • getPlatformInfo
    • getURL
    • openOptionsPage
    • reload
    • requestUpdateCheck
    • restart
    • restartAfterDelay
    • sendMessage
    • sendNativeMessage
    • setUninstallURL
    • onBrowserUpdateAvailable
    • onConnect
    • onConnectExternal
    • onConnectNative
    • onInstalled
    • onMessage
    • onMessageExternal
    • onRestartRequired
    • onStartup
    • onSuspend
    • onSuspendCanceled
    • onUpdateAvailable

    # Overview

    The Runtime API provides methods to support a number of areas of functionality that your extensions can use:

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

    See Message Passing for an overview of the subject.

    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 These methods are available only on ChromeOS, and exist mainly to support kiosk implementations. Methods in this category include restart and restartAfterDelay.

    # Permissions

    Most methods on the Runtime API do not require any permission, except for sendNativeMessage and connectNative, which require the nativeMessaging permission.

    # Manifest

    The following example shows how to declare the nativeMessaging permission in the manifest:

     
    "name": "My extension",
    .
    "permissions": [
    "nativeMessaging"
    ],
    .
    >

    # Use cases

    # 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 (e.g. ). 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.

     
    .
    "web_accessible_resources": [

    "resources": [ "logo.png" ],
    "matches": [ "https://*/*" ]
    >
    ],
    .
    >
     // Block used to avoid setting global variables 
    const img = document.createElement('img');
    img.src = chrome.runtime.getURL('logo.png');
    document.body.append(img);
    >

    # Send data from the service worker to a content script

    Its common for an extension’s content scripts to need data managed by another part of the extension, like the service worker. Much like two browser windows opened to the same web page, these two contexts cannot directly access each other’s values. Instead, the extension can use message passing to coordinate across these different contexts.

    In this example, the content script needs some data from the extension’s service worker to initialize its UI. To get this data, it passes a get-user-data message to the service worker, and it responds with a copy of the user’s information.

    // 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);
    >);
    // 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.

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

    # Extension examples

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

    Источник

    Debugging JavaScript Events With Chrome and Its Extensions

    I was refactoring ActiveCollab’s datepicker and came across a problem: to close the popover, I’d always have to trigger one extra keypress event.

    Chrome’s debugger

    Commonly, you’d use JavaScript to attach an event handler to do something when you click a button on a web page. You’d create a button, add some JavaScript to capture the click, and then execute a function.

    However, we have a problem when those buttons start piling up: with so many elements, it’s hard to see what happens where and why.

    Fortunately, Chrome’s DevTools have their own debugger.

    It’s easy to issue a `debugger` statement anywhere in the code and stop the JavaScript execution at a particular line. From there, you can see your local variables and stack trace up to the point where debugger stopped. You can step over and into functions, just like in any other debugger.

    Solving the problem with events

    The problem with events (or with pub/sub pattern in general) is that you can’t really be sure who’s listening to data changes that the publisher emits.

    First I tried DOM Breakpoint, a breakpoint that activates on DOM changes (attribute, node content, etc.). It didn’t work.

    After some time, I stumbled upon a lesser-known DevTools’ function: `monitorEvents()`.

    The monitorEvents() method instructs the DevTools to log information on the specified targets. The first parameter is the object to monitor. All events return if the second parameter is not provided. To specify the events to listen to you may pass either a string or an array of strings as the second parameter.
    — Chrome Developer Tools docs

    Translated to plain English — open the console, find an element whose events you’d like to debug (in my case ‘body’, so I see them all), and call:

    monitorEvents(document.getElementsByTagName(‘body’)[0], ‘mouse’)

    This monitors all mouse events (enter, leave, click, dblclick…) and log their contents to the console from where you can inspect them.

    This sometimes helps, but in my case, it didn’t: I had every info about the event but none about its callers.

    The Solution

    To get the callers, I used Event Listener Breakpoints, a panel in DevTools’ Sources tab (which does the same as pausing the execution on every page event).

    There I could scope the event type as I needed and break only on click events, keypresses, etc.

    It turned out to be the right solution — the source of my frustration was the Vimium chrome extension, which attaches itself outside the « and adds its own event listeners to «.

    So, the whole problem was that I was trying to inspect events on the « and I skipped the one that was causing misbehavior because I didn’t take into the account other things that could affect the environment.

    TL;DR: Turn off extensions when you’re developing stuff. Or develop in incognito mode.

    P.S. Remember to turn any Event Listener Breakpoints off after you’re done debugging because they persist and are turned on every time you start the browser

    Источник

    Читайте также:  Php fatal error cannot make static method non static
Оцените статью