访问Hotkey对象中的选定文本

时间:2013-09-17 22:39:36

标签: javascript firefox-addon firefox-addon-sdk hotkeys

是否可以在Hotkey的范围内抓取用户选定的文字?
Addon/lib/main.js中定义:

var showHotKey = Hotkey({
    combo: "accel-f1",
    onPress: function() {
        Addon.saveText(window.getSelection().toString());
    }
});

错误..

error: Addon: An exception occurred.
ReferenceError: window is not defined
resource://org/Addon/lib/main.js 14
Traceback (most recent call last):
File "resource://gre/modules/commonjs/sdk/keyboard/observer.js", line 39, in handleEvent
    this._emit(event.type, event, event.target.ownerDocument.defaultView);
File "resource://gre/modules/commonjs/sdk/deprecated/events.js", line 123, in _emit
    return this._emitOnObject.apply(this, args);
File "resource://gre/modules/commonjs/sdk/deprecated/events.js", line 153, in _emitOnObject
    listener.apply(targetObj, params);
File "resource://gre/modules/commonjs/sdk/keyboard/hotkeys.js", line 103, in onKeypress
    hotkey();
File "resource://org/Addon/lib/main.js", line 14, in showHotKey<.onPress
    Addon.saveText(window.getSelection().toString());

1 个答案:

答案 0 :(得分:2)

是的,最简单的方法是使用selection模块。

var { Hotkey } = require("sdk/hotkeys");
var selection = require("sdk/selection");

var showHotKey = Hotkey({
    combo: "accel-f1",
    onPress: function() {
        console.error(selection.text);
    }
});

如果您需要更复杂的内容,请查看tabs.activeTab.attach(),其中有一个示例,说明如何与活动标签进行交互。