Accessing Global Variables in Firefox Extensions

I am writing a Firefox extension that takes a custom switch from the command line and sets a variable inside my cmdline.js in the components directory, we will call the variable switchDetected , which is logical. Now, based on this variable, I want the actions to be performed in my overlay.js file in the chrome/content directory. The problem I am facing is that I cannot access the switchDetected variable declared in components/cmdline.js from chrome/contents/overlay.js .

I tried many ways to do this, but nothing works. So I'm just wondering if anyone knows how this can be achieved.

+4
source share
1 answer

A script loaded in the overlay is executed in the context of the browser window - its global variables are stored as properties of the window object corresponding to the browser. If you open a second browser window, the same script will be loaded a second time and run in the context of a new browser window - it will have different global variables. On the other hand, scripts containing XPCOM components are loaded only once, and they have their own independent context, which is not tied to the window. Therefore, their global variables cannot be accessed directly from the browser window, just as two browser windows cannot directly access each other's global variables.

Instead, the browser window should interact with the XPCOM component using the usual approach: get an instance of the component and call its method. If you don't want to define your own interface for this (you probably aren't), you can use a trick , something like this:

 CommandLineHandler.prototype = { handle: function(commandLine) {...}, get helpInfo() {...}, isSwitchDetected: function() { return switchDetected; }, get wrappedJSObject() { return this; }, QueryInterface: XPCOMUtils.generateQI(["nsICommandLineHandler"]); }; 

The wrappedJSObject property ensures that your component can be unpacked - all its methods and properties will become available, not just those defined in the interface. Therefore, your overlay script should do the following:

 var cmdLineHandler = Components.classes["@myself.com/my-command-line-handler;1"] .getService() .wrappedJSObject; var switchDetected = cmdLineHandler.isSwitchDetected(); 
+4
source

Source: https://habr.com/ru/post/1400378/


All Articles