Embedding NPAPI plugin in background using just Firefox Addon SDK

99封情书 提交于 2019-12-01 12:12:40

You'll want to look at the page-worker module:

https://addons.mozilla.org/en-US/developers/docs/sdk/1.8/packages/addon-kit/page-worker.html

The caveat I would give is that the NPAPI plugin might have made assumptions about visibility or other details of the environment it is running in that simply don't apply in the page-worker environment. If you run into errors, I'd be interested to hear them!

The following code provides a minimal working solution to the problem using the page-workers as as canuckistani suggested.

Note: This solution requires the addon-sdk's unsafeWindow to access the plugin member methods. If there's a better solution that does not depend on that, feel free to send a me a note/comment.

data/background.html

<html>
    <head>
        <script type="text/javascript" charset="utf-8">
            function pluginLoaded() {
                // Create an event once plugin is loaded
                // This allows the contentscript to detect plugin state
                var evt = document.createEvent("CustomEvent");
                evt.initCustomEvent("pluginLoaded", true, false, null);
                window.dispatchEvent(evt);
            }   
        </script>
    </head>
    <body>
        <object id="myplugin" type="application/x-myplugin" width="0" height="0">
            <param name="onload" value="pluginLoaded" />
        </object>
    </body>
</html>

data/background.js var module = null;

window.addEventListener("pluginLoaded", function( event ) {
    // set the module through unsafeWindow
    module = unsafeWindow.document.getElementById("myplugin");
    module = XPCNativeWrapper.unwrap(module);
    self.port.emit("pluginLoaded");
});

// Handle incoming requests to the plugin
self.port.on("pluginCall", function(msg) {
    var response; 
    if (module) {
        // Call NPAPI-plugin member method
        response = module[msg.method].apply(this, msg.args);
    } else {
        response = {error: true, error_msg: "Module not loaded!"};
    }
    self.port.emit("pluginResponse", {data: response});
});

main.js

// Create background page that loads NPAPI plugin
var plugin = require("page-worker").Page({
    contentURL: data.url("background.html"),
    contentScriptFile: data.url("background.js"),
    contentScriptWhen: "ready"
});

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