Firefox WebExtension:contextMenus中的selectionText只返回150个字符

时间:2017-08-07 15:26:25

标签: javascript firefox contextmenu firefox-webextensions textselection

我已经为Firefox(52.2.1 32位)构建了一个小型WebExtension,主要基于example provided by the Mozilla Developers Network。它是一个ContextMenu,它允许用户复制多个文本(通过选择相应的文本,然后选择上下文菜单中的一个按钮),并最终将它们(以某种方式)组合在剪贴板中以供进一步使用。 / p>

扩展程序工作正常,但现在单独选择和复制的文本突然限制为150个字符,所有选择的内容都被切断了。什么可能导致这种行为?

到目前为止,我找不到任何说明selectionText只存储150个字符的文档或论坛。

这是将所选文本复制到局部变量的方式:

browser.contextMenus.onClicked.addListener(function(info, tab) {
  if (info.menuItemId == "save-title") {
    title = info.selectionText;
  }
});

其余代码与上面链接的示例大致相同:

browser.contextMenus.onClicked.addListener(function(info, tab) {
  if (info.menuItemId == "export-to-clipboard") {
    const content = title + "\t" + date + "\t" + author + "\t\t" + abstract;

    const code = "copyToClipboard(" +
        JSON.stringify(content) + ");";

    browser.tabs.executeScript({
        code: "typeof copyToClipboard === 'function';",
    }).then(function(results) {
        // The content script's last expression will be true if the function
        // has been defined. If this is not the case, then we need to run
        // clipboard-helper.js to define function copyToClipboard.
        if (!results || results[0] !== true) {
            return browser.tabs.executeScript(tab.id, {
                file: "clipboard-helper.js",
            });
        }
    }).then(function() {
        return browser.tabs.executeScript(tab.id, {
            code,
        });
    }).catch(function(error) {
        // This could happen if the extension is not allowed to run code in
        // the page, for example if the tab is a privileged page.
        console.error("Failed to copy text: " + error);
    });
    title = "";
    date = "";
    author = "";
    abstract = "";
  }
});

并且,为了在此处包含所有内容,需要剪贴板--helper.js:

/* Copy-paste from https://github.com/mdn/webextensions-examples/blob/master/context-menu-copy-link-with-types/clipboard-helper.js */

// This function must be called in a visible page, such as a browserAction popup
// or a content script. Calling it in a background page has no effect!
function copyToClipboard(text) {
    function oncopy(event) {
        document.removeEventListener("copy", oncopy, true);
        // Hide the event from the page to prevent tampering.
        event.stopImmediatePropagation();

        // Overwrite the clipboard content.
        event.preventDefault();
        event.clipboardData.setData("text/plain", text);
    }
    document.addEventListener("copy", oncopy, true);

    // Requires the clipboardWrite permission, or a user gesture:
    document.execCommand("copy");
}

1 个答案:

答案 0 :(得分:2)

这在Firefox 56中已修复,请参阅: https://bugzilla.mozilla.org/show_bug.cgi?id=1338898