2

我经常想一次保存一组链接,并将 URL 和标题格式化为单个超链接 我正在开发一个 chrome 扩展,它将复制格式化的 url 和标题

清单.json

{
  "name": "Copy Tabs",
  "version": "0.1",
  "description": "Creates a keyboard shortcut (Ctrl + Shift + C) which copies links for selected tabs",
  "permissions": [
    "tabs",
    "clipboardWrite",
    "clipboardRead"
  ],
  "background": {
    "persistent": false,
    "scripts": ["jquery.js","background.js"]
  },
  "commands": {
    "copy-tabs": {
      "suggested_key": { "default": "Ctrl+Shift+C" },
      "description": "Copy Selected Tab Links"
    }
  },
  "manifest_version": 2
}

背景.js

chrome.commands.onCommand.addListener(function(command) {
  if (command == "copy-tabs") {
    // declare text element
    var text = "";

    // only look for highlighted tabs in the current window
    queryInfo = new Object();
    queryInfo.highlighted  = true;
    queryInfo.currentWindow  = true;

    // get tabs
    chrome.tabs.query(queryInfo, function(tabs) {
        // loop through tab results
        for (var i = 0; i < tabs.length; i++) {
            //add hyperlink to text
            text += "<a href='" + tabs[i].url + "'>" + tabs[i].title + "</a>";
        }
    });

    //copy text to clipboard
    copyTextToClipboard(text);
  }
});

复制文本到剪贴板

// Copy provided text to the clipboard.
function copyTextToClipboard(text) {
    var copyFrom = $('<textarea/>');
    copyFrom.text(text);
    $('body').append(copyFrom);
    copyFrom.select();
    document.execCommand('copy');
    copyFrom.remove();
}

问题:

我有两个问题:当我从选项卡属性构建链接时,副本实际上不起作用,但如果我手动指定text = "<a href='www.google.com'>Google</a>";一切正常。在开发人员工具中,内联工具提示看起来文本格式正确,但局部变量窗口看起来仍将文本变量设置为"".

内联手表 范围变量

其次,当它粘贴时,我没有得到很好的格式。

它看起来像这样:

  • <a href='www.google.com'>Google</a>

但我想要的是这样的:

4

1 回答 1

2

关于这两个问题:

  1. chrome.tabs.query是异步的。如果您不明白这一点,请阅读此类似问题。解决方案是copyTextToClipboard(text);chrome.tabs.query.
  2. 您正在execCommand('copy')文本区域上运行。结果是只有纯文本被复制到剪贴板。
    假设 HTML 输入来自受信任的,您可以使用以下代码将自定义富文本复制到剪贴板:

    function copyTextToClipboard(html) {
        var tmpNode = document.createElement('div');
        tmpNode.innerHTML = html;
        document.body.appendChild(tmpNode);
    
        // Back up previous selection
        var selection = window.getSelection();
        var backupRange;
        if (selection.rangeCount) {
            backupRange = selection.getRangeAt(0).cloneRange();
        }
    
        // Copy the contents
        var copyFrom = document.createRange();
        copyFrom.selectNodeContents(tmpNode)
        selection.removeAllRanges();
        selection.addRange(copyFrom);
        document.execCommand('copy');
    
        // Clean-up
        tmpNode.parentNode.removeChild(tmpNode);
    
        // Restore selection
        selection = window.getSelection();
        selection.removeAllRanges();
        if (backupRange) {
            selection.addRange(backupRange);
        }
    }
    
于 2013-07-14T22:24:51.170 回答