首页 文章

如何使用Firefox Add-On SDK获取所选文本?

提问于
浏览
3

我正在尝试使用在线Add-On SDK创建一个Firefox插件 .

我从一些简单的东西开始 - 我想添加一个工具栏按钮来读取当前选定的文本 .

documentation for the Selection对象使这看起来很简单:

var selection = require("selection");
if (selection.text)
  console.log(selection.text);

这对我来说似乎没有用,我只是得到 null .

这是我的完整代码:

var selection = require("selection");

require("widget").Widget({
    id: "widgetID1",
    label: "Test Mozilla Widget",
    contentURL: "http://www.mozilla.org/favicon.ico",
    onClick: function(event) {
        console.log('selection.text = ' + selection.text);
    }
});

我也尝试在 onClick 中创建 selection 对象,效果相同 .
我可以使用select事件来获得有关新选择的通知,所以我想我可以使用它来代替(并保留值),但我想知道为什么上面的代码不起作用...我做错了什么?

2 回答

  • 8

    定义的 selection 变量只有选中的文本才会有焦点 . 单击窗口小部件图标会使焦点远离所选文本,因此它不会选择任何文本 .

    这就是为什么它在侦听器函数中使用时有效 .

    为了确认这一点,我尝试在按下工具栏按钮时使用toolbarbutton module记录其值,并且它可以正常工作 . 按下工具栏按钮(大概)不会窃取焦点 .

    这是代码,and you can test it online too

    var selection = require("selection");
    
    var tbb = require("toolbarbutton").ToolbarButton({
        id: "test",
        label: "test",
        image: "http://www.mozilla.org/favicon.ico",
        onCommand: function(event) {
          console.log('selection = ' + JSON.stringify(selection)); // works!
        }
    });
    
  • 2

    以下是使用 select 事件的解决方案:

    var selection = require("selection");
    
    var selectedText = '';
    
    function selectionChanged(event){
        //todo: check for selection.isContiguous
        selectedText = selection.text;
    }
    
    selection.on('select', selectionChanged);
    
    require("widget").Widget({
        id: "widgetID1",
        label: "Test Mozilla Widget",
        contentURL: "http://www.mozilla.org/favicon.ico",
        onClick: function(event) {
            console.log('Selection: ' + selectedText);
        }
    });
    

相关问题