开发者

xpcom array can transfer in different xul files?

开发者 https://www.devze.com 2023-01-02 16:42 出处:网络
Now I am developing a firefox extension, can I define a global array in a开发者_JAVA技巧 js with the main xul . and I found when I use it in another js with another xul , it could not worked , so I se

Now I am developing a firefox extension, can I define a global array in a开发者_JAVA技巧 js with the main xul . and I found when I use it in another js with another xul , it could not worked , so I searched the document of Firefox development. I found a common array can not be transfered between two js files with different xul files. and then I defined a xpcom mutablearray in a js:

var eleList = Components.classes["@mozilla.org/array;1"] .createInstance(Components.interfaces.nsIMutableArray);

but when I want to use it in another js : it still not work , why? Thank you very much!


The problem is that even when you create the mutable array, you are storing the reference to this array object in a variable in the context of the XUL that creates it. From the other XUL, you don't see that variable so you cannot access the array.

There are several solutions to access an object accross different contexts:

  • From one of the contexts, get a reference to the other context. For example, you have a variable defined in the main window (browser.xul overlay), you can get it from a sidebar by using the window manager to get a reference to the main window.

  • You can create your own XPCOM object, although this is not simple to do, specially for a simple case like yours

  • You can used JavaScript modules to create a global singleton.

You should consider looking into the JavaScript modules option. It's the easiest and most reliable way. It was introduced in Firefox 3.0 and you can do it using only JavaScript without having to create a XPCOM

Check here for more details:

https://developer.mozilla.org/en/JavaScript_code_modules/Using_JavaScript_code_modules

UPDATED:

Here are some more details about how to get a reference to the main window to see what variables defined in browser.xul.

You define the variable in the browser.xul overlay (main window):

myArray = [1, 2, 3];

Then from the sidebar xul, you can get a reference to the main window and access your variable using the reference:

var mainWindow = window.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
                    .getInterface(Components.interfaces.nsIWebNavigation)
                    .QueryInterface(Components.interfaces.nsIDocShellTreeItem)
                    .rootTreeItem
                    .QueryInterface(Components.interfaces.nsIInterfaceRequestor)
                    .getInterface(Components.interfaces.nsIDOMWindow);

var value = mainWindow.myArray[0];

These links might have useful information for you:

https://developer.mozilla.org/en/Working_with_windows_in_chrome_code

https://developer.mozilla.org/en/Code_snippets/Tabbed_browser

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号