Compiling a Chrome extension popup with background reference using Closure Compiler

Developing a Chrome extension involves working with the scripts background.js and popup.js.

Within background.js:

function foo(){
  // Performs some action
}

In popup.js:

var backgroundPage = chrome.extension.getBackgroundPage();
backgroundPage.foo();

If these two files are compiled separately, the backgroundPage.foo() reference will be broken as 'foo' is renamed differently in both background.js and popup.js.

The proper way to address this is by exporting foo in background.js using window["foo"] = foo;, yet avoiding exports for code obfuscation.

An attempt was made to compile both scripts in one run and split them into separate output files using --module:

java -jar compiler.jar
  --compilation_level ADVANCED_OPTIMIZATIONS--js background.js popup.js
  --module backgroundMin:1
  --module popupMin:1:backgroundMin

However, this method failed as the compiler couldn't recognize that backgroundPage in popup.js corresponds to window in background.js. Various annotations like @lends, @borrows, and @memberOf were attempted but didn't yield successful results.

Hence, the question remains: Can both background.js and popup.js be compiled so that foo() is renamed without exporting it or breaking the reference from popup.js?

Answer №1

Opting for the --module option seems to be the most effective route - I can't envision a superior one.

To ensure that renaming functions properly, consider extending the Window type as follows:

/** @extends {Window} */
function CustomWindow () {}

CustomWindow.prototype = window.prototype;

/** @return {void} */
CustomWindow.prototype.bar = function() {};

Subsequently, in background.js:

var bgPage =
    /** @type {CustomWindow} */ (chrome.extension.getBackgroundPage());
bgPage.bar();

The typecast should function correctly since CustomWindow is an extension of Window.

All of this code should be incorporated into your actual project. Avoid using an extern file as it may obstruct the renaming process.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

AngularJS checkbox problem

<div ng-repeat="item in selectedSizes" <input type="checkbox" id="ckl_{{item.id}}" ng-model="item.checked" ng-change="selectSizeEdit(product.sizeArray, item.id)" ng-if="(product.sizeArray.indexOf(item.id) > -1) ...

"Collaborative Drive" assistance within Google Apps Script

Currently, I am developing a JavaScript tool within Google Apps Script to analyze various document properties such as the validity of links and correct permissions settings. To achieve this, I have been utilizing the API outlined in https://developers.goog ...

Error message: When using the Three.JS STL Loader, an Uncaught TypeError occurs because the property 'scale' is being called on an undefined value

I am currently loading five elements using the STL Loader in order to create a table. My goal is to use dat.gui to adjust the scale of Tabletop.STL. Here is the code snippet: <!DOCTYPE html> <html lang="en> <head> <title& ...

Map Row is unreturned

I am having trouble when attempting to map a JSON response from a MySQL query as I am receiving no response: data: NULL This is the code in question: const audience = rows.map((row) => { db.query(CountAudiences, [row.campaign], function(err, count ...

Unable to send event from JavaScript to Component in Ionic

My goal is to notify a component that a script file has finished loading. My approach involves using the onload event of an element to dispatch an event. A service will then register an event listener for this event, waiting for clients to subscribe to an ...

Retrieve the AngularJS scope object by using an alternate scope object as the identifier

As I loop through an array of person objects using ng-repeat, imagine the array looks something like this: [{ "display_name": "John Smith", "status": "part-time", "bio": "I am a person. I do people stuff.", }, { "display_name": "Jane Doe", "stat ...

What is the best way to ensure my dropdown menu closes whenever a user clicks anywhere on the page? (javascript)

I have created a dropdown that appears when the user clicks on the input field, but I would like to remove the active class so that the dropdown disappears if the user clicks anywhere else on the page. Here is my code snippet: // drop-down menu functi ...

Switch the menu state to closed when we click outside of it while it's open

I'm currently working on a scenario involving a menu that toggles when a button is clicked. The issue I'm facing is that when I click on the menu button, it opens correctly. However, the problem arises with the following code: Whenever I click ...

Applying conditional statements to an array's parent elements during iterations in JavaScript

Here is my complete script for relevance. I am currently looping through an array from a JSON object and populating content into an HTML div based on the content's ID. The process works well, but I am facing an issue with the logic related to the par ...

AngularJS: Issues with data retrieval in parallel in $http get requests within a $.each loop

Attempting to fetch data for multiple IDs is the goal: (Simplified version, aiming to clarify) Controller: var idList = [39,40,41]; $.each(idList, function(key, value){ var dataObject = { type: "test", id: value }; var getData = DataFactor ...

Is it possible to generate a coordinate grid comprised of clickable div elements with HTML, CSS, and Javascript - with the option to utilize JQuery if necessary?

Here is a link to the code on JFiddle: http://jsfiddle.net/4v2n7wk9/1/ <html> <head> <title>Example of Grid Buttons</title> <script src="//code.jquery.com/jquery-1.10.2.js"></script> <script src="//code.jquery.com/ui ...

Trouble with event.preventDefault functionality

This snippet of code I'm working on is pretty basic, nothing too intricate. $("input#send").submit(function(event){ event.preventDefault(); $.ajax({ type: 'POST', url: add.php, data: data, succe ...

Tips for showcasing images within buttons in HTML

Currently, I am working on setting up a local web server to manage various functions in my car using a RPi 4. For this project, I am incorporating libraries such as nodejs, npm, express, ejs, and rpi-gpio. My goal is to utilize rpi-gpio to operate relays ...

Enhance your image viewing experience with a React component that smoothly zooms in on images without distorting their dimensions, all with

After searching extensively for a solution, I have been unable to find one that works. My current setup involves using React with Bootstrap. I am in need of a stateless functional component that can take an image path as input and return an img element. Th ...

Customizing the background color of rows in Node.js XLSX using the npm package

I am currently working on a project that involves reading an Excel sheet and then coloring specific rows based on backend data. While I have successfully been able to read the sheet and create a new one with updated information, I am facing issues when try ...

What is the best practice for AngularJs service methods: accepting an object or multiple parameters?

When creating Angular JS service methods, what is the recommended approach: accepting multiple parameters or utilizing an object? var getMessages = function (appid, userId, limit) { var data = { "appid": appid, "userId": userId, ...

The appearance of the check box remains stagnant visually

Having trouble with dynamically changing the state of a checkbox based on a database value. Even though the value changes after a button click, the visual state of the checkbox remains the same. Here is the link to the JSFiddle for testing: http://jsfiddle ...

Display a modal before leaving the page?

I need to display a modal message when a user navigates away from the page, triggered by a successful AJAX call. The issue is that if the message loads too quickly, the user may not have enough time to read it before being directed to another page. This is ...

An Error occurred: Unable to resolve all parameters for 'ComponentName': ([object Object], ?)

I am encountering an error that I can't seem to figure out. compiler.js:2175 Uncaught Error: Can't resolve all parameters for ClauseListComponent: ([object Object], ?). at syntaxError (compiler.js:2175) at CompileMetadataResolver._getDependencie ...

What could be the reason for the malfunction of the "includes" function in my JavaScript snake game

As a beginner in JavaScript, I've been learning CSS and HTML as well. I decided to practice my skills by creating a snake game without following any tutorials. I know my code might not be the best and lacks good practices, but I'm just doing this ...