Question

I am trying to use google closure library inside content script of chrome extension.

This is how content_scripts look like in manifest.json

 "content_scripts": [
    {
        "matches": ["<all_urls>"],
        "js": [
                "closure-library/closure/goog/base.js",
                "content.js"
              ]
    }

I get the below error:

goog.require could not find: goog.dom 

I think one option is to use closure-builder to compile content.js with closure code and use the single output file but I would need to do that after every change in my content.js.

Is there any other way to use closure library inside content script?

Edit:
Even when I use closure-builder approach, it does not work correctly. It is trying to look for deps.js on the domain from where current webpage came. Eg. in case of google.com, I get the error message as below:

GET https://www.google.co.in/deps.js 404 (Not Found)
goog.writeScriptTag_
goog.importScript_ 
(anonymous function)
Was it helpful?

Solution

In order to use closure library in our chrome extension, we created an empty source.js which only included all the modules from closure library that we required.

Sample source.js (source.js goes inside myproject directory.)

goog.provide('myproject.start')
goog.require('goog.dom');
goog.require('goog.dom.query');
goog.require('goog.net.XhrIo');

Then we used closure-builder on this file and closure-library source to generate a single output file which contained all the relevant source of all closure library modules we required.

Relevant command:

closure-library/closure/bin/build/closurebuilder.py \
  --root=closure-library/ \
  --root=myproject/ \
  --namespace="myproject.start"
  --output_mode=compiled
  --compilation_level=SIMPLE_OPTIMIZATIONS

Note, you cannot use ADVANCED_OPTIMIZATIONS otherwise all unused functions will be stripped off which is not what we want.

Include this in manifest.json

"js": [
                "compiled.js",
                "content.js"
              ]

So, we need to generate compiled.js only when we need to include some new module from closure-library code which was rare and not every time we change our content.js.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top