Creating a chrome browser plugin

Test if your chrome browser is ready

  1. Download Sample code by google
  2. install and test, or this

Anatomy of a plugin

As in this article
Anatomy of a plugin

Create a new chrome browser Plugin

Basically 4 steps are to be kept in mind

  1. Step 1 : Create a manifest.json file
  2. Step 2 : Create a background.js script
  3. Step 3 : Create a content.js script
  4. Step 4 : Interscript communication
  5. Step 5 : Settings & Storage

Step 1 : Create a manifest.json file

Important json variables are

  1. name
  2. version
  3. permissions
  4. browser_action
  5. content_scripts
  6. manifest_version
    Error: Error: The storage API will not work with a temporary addon ID. Please add an explicit addon ID to your manifest. For more information see https://mzl.la/3lPk1aE. options.js:15:13

Sample manifest.json

{
  "name": "Getting Started Example",
  "description": "Build an Extension!",
  "version": "1.0",
  "manifest_version": 3,
  "background": {
    "service_worker": "background.js"
  },
  "permissions": ["storage", "activeTab", "scripting"],
  "action": {
    "default_popup": "popup.html",
    "default_icon": {
      "16": "/images/get_started16.png",
      "32": "/images/get_started32.png",
      "48": "/images/get_started48.png",
      "128": "/images/get_started128.png"
    }
  },
  "icons": {
    "16": "/images/get_started16.png",
    "32": "/images/get_started32.png",
    "48": "/images/get_started48.png",
    "128": "/images/get_started128.png"
  },
    "content_scripts": [
        {
        "matches": [
            "http://*/*",
            "https://*/*"
            ],
        "js": ["content.js"],
        "run_at": "document_end",
        "all_frames": false   
        }
    ],
  "options_page": "options.html"
}

Step 2: Create a background.js script

let color = '#3aa757';
let timeOuts4Messaging;

chrome.runtime.onInstalled.addListener(() => {
  chrome.storage.sync.set({ color });
  console.log('Default background color set to %cgreen', `color: ${color}`);
});

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
    console.log(sender.tab ?
                "from a content script, URL is :" + sender.tab.url :
                "from the extension");
    console.log(request.greeting)
     if (request.greeting === "2.content2Bg")
     {
      sendResponse({farewell: "goodbye to content from bg"});// this will not work if called in popup
      timeOuts4Messaging = setTimeout(sendMessage2Content,1000)
     }
});
function sendMessage2Content()//https://developer.chrome.com/docs/extensions/mv3/messaging/
{
    chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
      chrome.tabs.sendMessage(tabs[0].id, {greeting: "3.bg2Content"}, function(response) {
        console.log(response.farewell);
      });
    });
    // to send to popup 'chrome.runtime' is used instead of chrome.tabs.sendMessage
    chrome.runtime.sendMessage({greeting: "5.bg2Popup"}, function(response) {
        console.log(response.farewell);
      });
    clearTimeout(timeOuts4Messaging);   
}

Step 3: Create a content.js script

chrome.runtime.onMessage.addListener( //https://developer.chrome.com/docs/extensions/mv3/messaging/
  function(request, sender, sendResponse) {
    console.log(sender.tab ?
                "from a content script, URL is :" + sender.tab.url :
                "from the extension");
    console.log(request.greeting);
    if (request.greeting === "1.popup2Content")
    {       
      sendResponse({farewell: "goodbye to popup from content"});
      send2Bg();
    }
    if (request.greeting === "3.bg2Content")
    {
      sendResponse({farewell: "goodbye to BG  from content"});      
    }   
  }
);
function send2Bg()
{
    chrome.runtime.sendMessage({greeting: "2.content2Bg"}, function(response) {
        console.log(response.farewell);
        timeOuts4Messaging = setTimeout(send2Popup,1000)
      });
}
function send2Popup()
{
    chrome.runtime.sendMessage({greeting: "4.content2Popup"}, function(response) {
        console.log(response.farewell);
      });
}
//console.log("contest is loaded");

Step 3: popup.js

// Initialize butotn with users's prefered color
let changeColor = document.getElementById("changeColor");
chrome.storage.sync.get("color", ({ color }) => {
  changeColor.style.backgroundColor = color;
});
// When the button is clicked, inject setPageBackgroundColor into current page
changeColor.addEventListener("click", async () => {
  sendMessage2Content();
  let [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
  chrome.scripting.executeScript({
    target: { tabId: tab.id },
    function: setPageBackgroundColor,
  });
});
// The body of this function will be execuetd as a content script inside the
// current page
function setPageBackgroundColor() { 
  chrome.storage.sync.get("color", ({ color }) => {
    document.body.style.backgroundColor = color;
  });
}
function sendMessage2Content()//https://developer.chrome.com/docs/extensions/mv3/messaging/
{
    chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
      chrome.tabs.sendMessage(tabs[0].id, {greeting: "1.popup2Content"}, function(response) {
        console.log(response.farewell);
      });
    });
}
chrome.runtime.onMessage.addListener( //https://developer.chrome.com/docs/extensions/mv3/messaging/
  function(request, sender, sendResponse) {
    console.log(sender.tab ?
                "from a content script, URL is :" + sender.tab.url :
                "from the extension");
    console.log(request.greeting);
    if (request.greeting === "4.content2Popup")
    {       
      sendResponse({farewell: "goodbye to content from popup"});    
    }
    if (request.greeting === "5.bg2Popup")
      sendResponse({farewell: "goodbye to BG  from popup"});   
  }
);

Interscript communication

  1. To send message from content to background or popup

    chrome.runtime.sendMessage
  2. To send ro content from background or popup

    chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
      chrome.tabs.sendMessage(tabs[0].id, {greeting: "1.popup2Content"}, function(response) {
        console.log(response.farewell);
      });
    });
  3. set listener

    chrome.runtime.onMessage.addListener( //https://developer.chrome.com/docs/extensions/mv3/messaging/
    function(request, sender, sendResponse) {
    console.log(sender.tab ?
                "from a content script, URL is :" + sender.tab.url :
                "from the extension");
    console.log(request.greeting);
    if (request.greeting === "4.content2Popup")
    {       
      sendResponse({farewell: "goodbye to content from popup"});    
    }
    if (request.greeting === "5.bg2Popup")
      sendResponse({farewell: "goodbye to BG  from popup"});   
    }
    );
  4. send reply message to content

    sendResponse({farewell: "goodbye to BG  from popup"});  
  5. send response after executing required function

function sendMessage2Content()//https://developer.chrome.com/docs/extensions/mv3/messaging/
{
    chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
      chrome.tabs.sendMessage(tabs[0].id, {greeting: "3.bg2Content"}, function(response) {
        console.log(response.farewell);
      });
    });
    // to send to popup 'chrome.runtime' is used instead of chrome.tabs.sendMessage
    chrome.runtime.sendMessage({greeting: "5.bg2Popup"}, function(response) {
        console.log(response.farewell);
      });
    clearTimeout(timeOuts4Messaging);

}

Step 4: Settings & Storage

Add manifest.json keys to setup a settings page

  1. in manifest.json, add the following
  "options_page": "options.html",
  "permissions": ["storage"],
  1. code to set option value in storage
chrome.storage.sync.set({ "color" : '#3aa757' });// code to set value in storage
  1. code to retrieve from storage
    chrome.storage.sync.get("color", (data) => {
    let currentColor = data.color;

References

  1. Intro
  2. Interscript communication
  3. For setting up a settings page with storage
  4. Anatomy of a firefox browser plugin
  5. Background scripts
  6. Content scripts
  7. Options
  8. User Interface
  9. Popup
  10. Persistant Connections ie port