Search code examples
javascriptgoogle-chrome-extensionfirefox-addonbrowser-extension

Initialize an instance after running a custom script from a Chrome Extension?


I want to initialize an instance which is in my customScript.js from my contentScript.js.

I followed https://stackoverflow.com/a/9517879/6141587 but still have doubts.

Here's my code →

background.js

chrome.browserAction.onClicked.addListener(function(tab) {
    chrome.tabs.executeScript(tab.id, {
       file: 'contentScript.js',
    })
})

browser.runtime.onMessage.addListener(function(request, sender, sendResponse) {
  if (request.subject === 'animalInit') animal.init()
})

manifest.json

{
  ...
  "background": {
    "scripts": ["background.js"],
    "persistent": false
  },
  "browser_action": {},
  "permissions": ["activeTab", "https://*/*", "http://*/*"],
  "web_accessible_resources": ["style.css", "customScript.js"],
    ...
}

customScript.js

function animalClass() {
    this.init = function() {
        console.log('animal.init()')
    }
}

var animal = new animalClass()
window.animal = animal

contentScript.js

const body = document.getElementsByTagName('body')[0]
const button = document.createElement('button')
body.appendChild(button)

button.addEventListener('click', function() {
    chrome.runtime.sendMessage({ subject: 'animalInit' })
})

I currently get error animal is not defined.

I basically want to run the function animal.init() from customScript.js on a click of a button in contentScript.js.

Idk how this is possible. Any ideas?


Solution

  • Found the solution. I am using parcel-bundler so import & export works fine.

    All I did was import customScript.js in contentScript.js & call it from there.

    background.js

    chrome.browserAction.onClicked.addListener(function(tab) {
        chrome.tabs.executeScript(tab.id, {
            file: 'contentScript.js',
          })
    })
    

    manifest.json

    {
      ...
      "background": {
        "scripts": ["background.js"],
        "persistent": false
      },
      "browser_action": {},
      "permissions": ["activeTab", "https://*/*", "http://*/*"],
      "web_accessible_resources": ["style.css", "customScript.js"],
        ...
    }
    

    customScript.js

    function animalClass() {
        this.init = function() {
            console.log('animal.init()')
        }
    }
    
    var animal = new animalClass()
    window.animal = animal
    module.exports = animal
    

    contentScript.js

    import animal from './customScript.js'
    
    const body = document.getElementsByTagName('body')[0]
    const button = document.createElement('button')
    body.appendChild(button)
    
    button.addEventListener('click', function() {
        animal.init()
    })