Search code examples
javascriptgoogle-chromegoogle-chrome-extensionvirtual-realitywebvr

Function declared on injected file not recognize from background.js in chrome extension


I'm trying to use https://github.com/povdocs/webvr-starter-kit to create a chrome PageAction extension.

On my manifest.json file, I've used content_scripts to load jquery.js and another inject.js.

On my inject.js, I've the following codes:

function initVR() {
    VR.floor();
    VR.box({ color: '#FFFFFF' }).moveTo(0, 1.4, 0).setScale(5,4,0);
    var text = VR.text({
        wrap: 4.1,
        font: '24pt Roboto',
        textAlign: 'left',
        fillStyle : '#000000',
        text : 'Hello world test'
    })
    .moveTo(.1, 1.4, 0);
}

on my background.js file, I've

chrome.pageAction.onClicked.addListener(function(tab) {
  chrome.tabs.executeScript(tab.ib, {
    file:  "src/inject/vr.dev.js"
  }, function(){
    initVR();    //Calling the function I declared on inject.js
});

The idea here is, when a person clicks on the pageAction button, it injects the vr.dev.js and initialize the setup.

When I implement this, I get an error saying initVR() is not defined. What am I doing incorrect?

enter image description here


Solution

  • You have to use message passing to communicate to content script,because the extension of your browser is a single background script,it have to identify the tab

    https://developer.chrome.com/extensions/messaging