开发者

Load an external JS library into a page using Greasemonkey

I want a translator in my Firefox. I find some code from internet. but it doesn't run in my Firefox. I have installed Greasemonkey.

function loadBingTranslator() {
    script = document.createElement('script');
    script.src = 'http://dict.bing.com.cn/cloudwidget/Scripts/Generated/Bin开发者_C百科gTranslate_Selection_ShowIcon.js';
    script.onload = initBingTranslator;
    document.body.appendChild(script);
};

function initBingTranslator() {
    BingCW.Init({
        MachineTranslation: true,
        WebDefinition: true
    });
}
loadBingTranslator();


Such a script must account for the GM sandbox, and also (usually) allow time for the library to load and initialize.   See Avoid Common Pitfalls (in Greasemonkey).

So, you would use this library like so:

//--- Load the library.
var D           = document;
var appTarg     = D.getElementsByTagName ('head')[0]  ||  D.body  ||  D.documentElement;
var jsNode      = D.createElement ('script');

jsNode.src      = 'http://dict.bing.com.cn/cloudwidget/Scripts/Generated/BingTranslate_Selection_ShowIcon.js';
jsNode.addEventListener ("load", initBingTranslatorOnDelay, false);

appTarg.appendChild (jsNode);


//--- Allow some time for the library to initialize after loading.
function initBingTranslatorOnDelay () {
    setTimeout (initBingTranslator, 666);
}

//--- Call the library's start-up function, if any. Note needed use of unsafeWindow.
function initBingTranslator () {
    unsafeWindow.BingCW.Init ( {
        AppID:              "GM Foo",
        MachineTranslation: true,
        WebDefinition:      true
    } );
}



Issues, some specific to this question:

  1. onload is not available; See the pitfalls. Event handlers cannot be set this way in GM. Also, addEventListener() is the best practice anyway.

  2. Accessing JS (including libraries we load) in the page scope, requires unsafeWindow.

  3. That app appears to want an AppID.

  4. Sometimes, libraries like this can be loaded in the GM scope instead of the page scope, using the // @require directive.
    I did not try that with this library, but with others, it may be possible.   Do not try this with untrusted libraries, as they gain extra abilities to infect your machine, once inside the GM scope.

  5. Don't use reserved words, like "script", for variable names.


My JavaScript Console is outputting a "Component is not available" line 10: script.onload = initBingTranslator;

So I fixed changed it to ... = initBingTranslator() because it is a function.

Now it says "BingCW is not definded" Line 15: BingCW.Init({ MachineTranslation: true, WebDefinition: true });

And it is right, not sure if something is missing or this is supposed to only work in IE, I would find a Google translator solution personally (or just use an existing add-on).


Bing Dictionary hasd published a Firefox addon. You can use it directly.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜