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 →
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()
})
{
...
"background": {
"scripts": ["background.js"],
"persistent": false
},
"browser_action": {},
"permissions": ["activeTab", "https://*/*", "http://*/*"],
"web_accessible_resources": ["style.css", "customScript.js"],
...
}
function animalClass() {
this.init = function() {
console.log('animal.init()')
}
}
var animal = new animalClass()
window.animal = animal
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?
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.
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.tabs.executeScript(tab.id, {
file: 'contentScript.js',
})
})
{
...
"background": {
"scripts": ["background.js"],
"persistent": false
},
"browser_action": {},
"permissions": ["activeTab", "https://*/*", "http://*/*"],
"web_accessible_resources": ["style.css", "customScript.js"],
...
}
function animalClass() {
this.init = function() {
console.log('animal.init()')
}
}
var animal = new animalClass()
window.animal = animal
module.exports = animal
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()
})