剪贴板复制/粘贴内容脚本(Chrome扩展程序)

Yav*_*hev 11 google-chrome-extension content-script

我正在使用内容脚本来操纵DOM中的数据.我一直在使用document.execCommand('copy'); 在弹出页面上成功完成.

我现在正在寻找一种方法使其适用于内容脚本.我已经检查内容脚本的限制在这里,但如果剪贴板控制是有限的或不是我不明白.我也在这里检查了答案 - 在stackoverflow中,但似乎大多数是不确定的,有些是几年前的,所以可能有变化.

即使它有限,是否可以采取某种解决方法?

谢谢!

我发布了我当前的脚本.

的manifest.json

{
  "name": "Page action by URL",
  "version": "1.0",
  "description": "???????? ?? ????????? ?? ??????? ?? ????.",
  "background": {
    "scripts": ["background.js"],
    "persistent": false
  },
  "page_action" :
  {
    "default_icon" : "icon-19.png",
    "default_title" : "?????????? ?? ??? ?? PHP"
  },
  "permissions" : [
    "clipboardWrite",
    "clipboardRead",
    "declarativeContent",
    "activeTab",
    "tabs",
    "https://nbd.grao.government.bg/graoappshort/*"
  ],
  "icons" : {
    "48" : "icon-48.png",
    "128" : "icon-128.png"
  },
  "manifest_version": 2
}
Run Code Online (Sandbox Code Playgroud)

background.js

chrome.runtime.onInstalled.addListener(function() {
  // Replace all rules ...
  chrome.declarativeContent.onPageChanged.removeRules(undefined, function() {
    // With a new rule ...
    chrome.declarativeContent.onPageChanged.addRules([
      {
        conditions: [
          new chrome.declarativeContent.PageStateMatcher({
            pageUrl: { urlContains: 'nbd.grao.government.bg/graoappshort/' },
          })
        ],
        actions: [ new chrome.declarativeContent.ShowPageAction() ]
      }
    ]);
  });
});


chrome.pageAction.onClicked.addListener(function(tab) {
  chrome.tabs.executeScript(null, {file: 'page-editor.js'});
  chrome.tabs.insertCSS(null, {file: "style-inject.css"});
});
Run Code Online (Sandbox Code Playgroud)

以及page-editor.js中的函数

function(){
      var copyFrom = document.createElement("textarea");
      copyFrom.textContent = PoleIME.value;
      document.body.appendChild(copyFrom);
      copyFrom.focus();
      document.execCommand('SelectAll');
      document.execCommand('Copy');
      //document.body.removeChild(copyFrom);
      }
Run Code Online (Sandbox Code Playgroud)

Rob*_*b W 23

内容脚本此刻无法使用剪贴板.将来,一旦crbug.com/395376得到解决,那么问题中显示的代码将按预期工作.

在修复该错误之前,您必须将数据发送到后台页面并从那里复制文本:

// content script
chrome.runtime.sendMessage({
    type: 'copy',
    text: 'some text to copy'
});
Run Code Online (Sandbox Code Playgroud)

背景页面活动页面上的脚本:

chrome.runtime.onMessage.addListener(function(message) {
    if (message && message.type == 'copy') {
        var input = document.createElement('textarea');
        document.body.appendChild(input);
        input.value = message.text;
        input.focus();
        input.select();
        document.execCommand('Copy');
        input.remove();
    }
});
Run Code Online (Sandbox Code Playgroud)

  • 该错误自2014年9月起已修复 (2认同)