How to copy to clipboard via chrome.notification.c

2019-09-15 01:45发布

Testpage: https://www.google.com

It works in Chrome but in Firefox Nightly 52.0a1 it gives me this error when clicked on the notification:

document.execCommand(‘cut’/‘copy’) was denied because it was not called from inside a short running user-generated event handler

copyTextToClipboard() function was taken from Copy to Clipboard in Chrome Extension

manifest.js

{
    "description": "Test for JSON Notifiaction + Clipboard Copy",
    "manifest_version": 2,
    "name": "Test3",
    "version": "1.0",

    "permissions": [
        "<all_urls>",
        "clipboardWrite",
        "notifications",
        "webRequest"
    ],

    "background": {
        "scripts": ["background.js"]
    }
}

background.js

'use strict';
let JSON_obj = {
        "name" : "ABCDEFG",
        "age"  : 3,
          };

function logURL(requestDetails) {
     // filter rules to check requestDetails.url for specific parameters {
        notify(JSON_obj);
     // }
}

function notify(notifyMessage) {
    var options = {
        type: "basic",
        iconUrl: chrome.extension.getURL("icons/test.png"),
        title: "",
        message: JSON.stringify(notifyMessage, null, "\t")
    };

    chrome.notifications.create("uniqueID3", options);
}

chrome.notifications.onClicked.addListener(function() {
    console.log('Clicked notification message text: ', JSON_obj);
    copyTextToClipboard(JSON.stringify(JSON_obj, null, "\t"));
});

function copyTextToClipboard(copyText) {
    var copyFrom = document.createElement("textarea");
    copyFrom.textContent = copyText;
    var body = document.getElementsByTagName('body')[0];
    body.appendChild(copyFrom);
    copyFrom.select();
    document.execCommand('copy');
    body.removeChild(copyFrom);
    }


chrome.webRequest.onBeforeRequest.addListener(
    logURL, {
        urls: ["<all_urls>"]
    }
);

1条回答
Root(大扎)
2楼-- · 2019-09-15 02:36
登录 后发表回答