Browser extension to print 'Hello World' not working

38 Views Asked by At

Trying to create a simple browser extension in Chrome. Expected functionality:

  1. Opening a new tab, typing 'HW' in the URL bar should trigger the extension.
  2. It should show 'Hello World' on the web page of the browser tab and not as a pop-up.

Based on what I have tried so far, on triggering the extension, nothing happens on the web page and none of the console.log messages show up in Console / Network tab in Developer Tools.

Here is what I have tried so far:

Directory structure of source files: test-extn (directory) has 2 files:

  1. manifest.json
  2. background.js

manifest.json

{
  "manifest_version": 3,
  "name": "Hello World Extension",
  "version": "1.0",
  "description": "Prints 'Hello World' in the tab.",
  "permissions": [
    "activeTab",
    "scripting"
  ],
  "background": {
    "service_worker": "background.js"
  },
  "omnibox": {
    "keyword": "HW"
  }
}

background.js

// Log to confirm that the service worker is loaded
console.log('Service Worker Loaded');

chrome.omnibox.onInputEntered.addListener((text) => {
  console.log('Inside listener')
  if (text === 'HW') {
    chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
      chrome.scripting.executeScript({
        target: { tabId: tabs[0].id },
        function: () => {
          document.body.innerHTML = "<h1>Hello World</h1>";
        }
      });
    });
  }
});

Loading the extension and triggering it

  1. Loaded chrome://extensions/ in Chrome.
  2. Enabled 'Developer mode'.
  3. Clicked 'Load unpacked' and added my extension folder.
  4. Opened a new tab in Chrome. On typing HW in the Omnibox(URL bar) and hitting tab, I see 'Hello World Extension'. Then on hitting Enter, nothing happens. Whereas the expected behavior was to show 'Hello World' on the web page.

What I am observing:

chrome://serviceworker-internals/ shows the following

Scope: chrome-extension://nfhcnmooaafbclgdgaaibgppfhnphnkn/
Storage key:
Ancestor chain bit: SameSite
Registration ID: 111
Navigation preload enabled: false
Navigation preload header length: 4
Active worker:
Installation Status: ACTIVATED
Running Status: RUNNING
Fetch handler existence: DOES_NOT_EXIST
Fetch handler type: NO_HANDLER
Script: chrome-extension://nfhcnmooaafbclgdgaaibgppfhnphnkn/background.js
Version ID: 1342
Renderer process ID: 27755
Renderer thread ID: 1
DevTools agent route ID: 1

Based on above, it seems like the service worker (background.js) is registered, active and currently running.

I looked at both the Console and Network tab within Developer Tools. I don't see anything related to background.js or any of the 2 console.log messages the I have in background.js.

Not sure if the issue with how the Developer Tools is capturing the logs, or possibly an issue with the event triggering itself. Appreciate any help.

0

There are 0 best solutions below