0

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?

deadcoder0904
  • 7,232
  • 12
  • 66
  • 163
  • 1) The background script runs in a separate hidden background page with its own chrome-extension URL and an empty `document`, not related to the web page. 2) You can't access JS objects across the isolated world boundary so the only place where you can instantiate `animal` is inside customScript.js or another page script added as a ` – wOxxOm Jul 24 '19 at 17:05
  • thanks for the comment. i exported `animal` using `module.exports` & imported it in `contentScript.js` & called it from there without message passing. I am using a bundler (parcel) so it worked :) – deadcoder0904 Jul 25 '19 at 09:32

1 Answers1

0

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()
})
deadcoder0904
  • 7,232
  • 12
  • 66
  • 163
  • No, your imported customScript.js is just a normal content script now, it's not a [page script](https://stackoverflow.com/a/9517879) so either your question is about a totally different thing or this is not the solution you need. – wOxxOm Jul 25 '19 at 09:44
  • Ohh so this is not the solution I need I guess. This works for my use-case. What I want to do is basically insert a script on a page & then using a UI inserted by my Chrome Extension call the scripts methods like `animal.init()`. I also want the `animal` to be accessible via DevTools console if I type `window.animal`. Is it possible with `page_script`? – deadcoder0904 Jul 25 '19 at 09:48
  • I'll try to rephrase in a different fashion what I already wrote several times. A page script is just a standard ` – wOxxOm Jul 25 '19 at 10:00
  • Now I understood what you are saying. Page Scripts can't access anything from Content Scripts & vice-versa. And I'm only using Content Scripts in my example since I'm importing it. I forgot to mention one important point I'm doing is injecting `customScript.js` into DOM so I can access `window.animal` in DevTools Console. So the `customScript.js` is run twice. Once when I inject in the pages head & once in `contentScript.js` when I import `animal`. Idk if it's right but works for now ‍♂️ – deadcoder0904 Jul 25 '19 at 10:22
  • 1
    You can access the content script's global variables and `window` by switching the context in console: https://developers.google.com/web/tools/chrome-devtools/console/reference#context so maybe you don't need a page script at all. – wOxxOm Jul 25 '19 at 10:33
  • oh yes, didn't know about this, that's great but users are non-technical folks so a bit of a pain to make them use the UI. they know the console thing tho so should be easy to transition. – deadcoder0904 Jul 25 '19 at 10:43