Chrome Selection.addRange() 不选择 (execCommand('copy') 用例)



>在Chrome中编写一个小的浏览器扩展程序,将特定网页中的某些特定文本复制到剪贴板。在HTML格式中,因此人们可以将其粘贴到Office程序中,例如word,outlook等。

document.execCommand('copy')是我使用的命令,它是由document.onkeydown组合键(Alt+1)触发的,并且工作正常 - 但只是第一次。如果您尝试再次按组合键,它将不执行任何操作。

我已经找到了原因,document.queryCommandEnabled("copy")第一次返回 true,任何其他尝试都返回 false。如果我重新加载页面,它第一次再次返回 true。此外,如果我在加载页面后在浏览器窗口外单击,然后在浏览器中单击并使用组合键,则立即返回 false,即使是第一次。

function copy(text) {
var sel = document.createElement("div"); // Creating temporary holder for text to copy
sel.style.opacity = 0;             sel.style.position = "absolute";  // These are not really required,
sel.style.pointerEvents = "none";  sel.style.zIndex = -1;            // at least for Chrome
sel.innerHTML = text; // Put the text to copy into the temporary holder
document.body.appendChild(sel); // Add the temporary holder to the page
var range = document.createRange();     // All this is required to select the text,
range.selectNode(sel);                  // since the holder is not an editable text
window.getSelection().addRange(range);  // field and must be treated differently.
// document.designMode = 'on'; (Tried this, no effect)
/* Debugging */ alert("Enabled = " + document.queryCommandEnabled("copy") + " Design mode = " + document.designMode);
try {
document.execCommand('copy'); // Copy to clipbopard
}
catch (err) {
alert('Unable to copy');
console.log('Unable to copy'); // Copy failed?!
}
// document.designMode = 'off'; (Tried this, no effect)
document.body.removeChild(sel); // Clean up removing the temporary holder
}
document.onkeydown=function(e){
if(e.altKey && e.which == 49) { // Alt+1
copy(link_variable);
return false;
}
}

有什么想法吗?

添加清单文件:

{
"manifest_version": 2,
"name": "Usage text",
"version": "0.2",
"description": "Whatever",
"content_scripts": [
{
"matches": [
"*://some.specific.site.com/*"
],
"js": ["content.js"]
}
],
"background": {
"scripts": ["background.js"]
},
"browser_action": {
"name": "Whatever",
"default_icon": "icon.png"
},
"permissions": [
"tabs",
"clipboardWrite"
]
}

更新:

将操作从内容脚本转移到后台脚本,没有变化。

在尝试问题中的代码时,Chromium 59 记录了以下警告:

[弃用] Selection.addRange() 合并现有 Range 和指定 Range 的行为已被删除。有关更多详细信息,请参阅 https://www.chromestatus.com/features/6680566019653632。

  1. 引导我进入提到的Chrome状态

    在文档已经有文本选择并且调用了 Selection.addRange() 的情况下,如果 Range 和现有文本选择有重叠,Blink 会将它们合并为一个,否则不执行任何操作。我们将对其进行更改,以便 Blink 始终忽略范围。它与边缘匹配。

  2. 引导我讨论 W3C 规范

  3. 让我阅读了 W3C 规范。

根据规范addRange()如果已经有一个选择,则不应执行任何操作:

  1. 如果 rangeCount 不为 0,请中止这些步骤。

有趣的是,似乎已经有一个选择。检查window. getSelection().rangeCount确认了这一点。我无法解释为什么会这样,但这是问题中提到的问题的原因。

addRange()之前调用removeAllRanges()解决了问题:

var sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);

最新更新