I am writing a Chrome extension with background.js
and popup.js
scripts.
In background.js
:
function foo(){
// Does something
}
In popup.js
:
var backgroundPage = chrome.extension.getBackgroundPage();
backgroundPage.foo();
Compiling these two files separate will, of course, break the backgroundPage.foo()
reference, because foo
gets renamed differently in background.js
and popup.js
.
I know the "correct" way to fix this would be to export foo
in background.js
using window["foo"] = foo;
, but I would like to avoid exports if possible (to make the code as unreadable as possible).
I've tried compiling both scripts in one run and splitting them into seperate output files using --module
:
java -jar compiler.jar
--compilation_level ADVANCED_OPTIMIZATIONS--js background.js popup.js
--module backgroundMin:1
--module popupMin:1:backgroundMin
Not surprisingly this doesn't work, because the compiler doesn't know that backgroundPage
in popup.js
is the same as window
in background.js
. I tried annotating using @lends
, @borrows
and @memberOf
, but haven't been able to get it to work.
So my question is: Is it possible to compile both background.js
and popup.js
so foo()
gets renamed - without exporting foo()
and without breaking the reference from popup.js
?
Using the --module
option is probably the best path - I can't think of a better one.
To get renaming to work correctly, you should be able to extend the Window type:
/** @extends {Window} */
function MyWindow () {}
MyWindow.prototype = window.prototype;
/** @return {void} */
MyWindow.prototype.foo = function() {};
Then in background.js
var backgroundPage =
/** @type {MyWindow} */ (chrome.extension.getBackgroundPage());
backgroundPage.foo();
The type cast should work here because MyWindow
extended Window
.
All of this would be placed in your actual code. Don't use an extern or that will block renaming.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.