how to call a function in Firefox extension from a html button

六眼飞鱼酱① 提交于 2019-12-18 21:17:44

问题


How to call a Javascript function declared in my extension, using a html button from my web page?

I have a html page, with a button inside. When the user click the button, it will call a function that I already declared inside my own firefox extension.


回答1:


Since you control the web page, the easiest and the safest method to do what you want would be to dispatch a custom DOM event in the web page and listen to it in the extension code:

https://developer.mozilla.org/En/Code_snippets/Interaction_between_privileged_and_non-privileged_pages

Here's an example extension I wrote that does exactly this http://mozilla.doslash.org/cw/ (not updated to the most recent Firefox version, but it's clean and should be easy to update).




回答2:


Your Firefox extension runs in a different Javascript context to your HTML page, so the extension cannot be directly called from the Javascript in your HTML page.

However, you can design the extension to allow access from HTML. HTML Javascript isn't generally allowed to access the Component object, so you need to allow the HTML code a way to get at the object in your extension. To do this, create an XPCOM component in your extension, and set the object in the "JavaScript global property" category through the nsICategoryManager object. The entry name is the string used from unprivileged Javascript, the value is the contract ID for your XPCOM class.

However, you also need to allow unprivileged Javascript access to your object, or the script security manager will block access. To allow this, implement nsISecurityCheckedComponent - providing canCreateWrapper(in nsIIDPtr iid), canCallMethod(in nsIIDPtr iid, in wstring methodName), canGetProperty(in nsIIDPtr iid, in wstring propertyName) and canSetProperty(in nsIIDPtr iid, in wstring propertyName) to return allAccess for the allowed properties, and noAccess otherwise.

Be careful what you do with user input, and what you allow access to - it is very easy to accidentally create a security hole in the browser doing this.




回答3:


Try to put this at the beginning of your javascript function that tries to access a local file:

netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');

This will give the user the choice as to whether they want to allow your code to access the local filesystem.



来源:https://stackoverflow.com/questions/2017743/how-to-call-a-function-in-firefox-extension-from-a-html-button

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!