0

I'm building an extension to copy text to the clipboard without including the line breaks. It runs on every URL but not on PDFs. Background script:

chrome.commands.onCommand.addListener(function (command) {
    if (command === "copy") {
        chrome.tabs.query({'currentWindow':true,'active':true}, function(tabs){
            chrome.tabs.sendMessage(tabs[0].id,'hi');
        })
        }
    }
);

Here is the content script:

async function copyPageUrl() {
  try {
    const text = navigator.clipboard
    yo = window.getSelection().toString();
    yon = yo.replace(/(\r\n|\n|\r)/gm, " ");
    await text.writeText(yon);
    console.log('Page URL copied to clipboard');
    console.log(yon);
  } catch (err) {
    console.error('Failed to copy: ', err);
  }
}

chrome.runtime.onMessage.addListener(function(request){
  alert(request);
  console.log('copy was pressed');
  copyPageUrl()
})

FYI, this is the manifest

{
    "name": "Line Break remover",
    "version": "1.0",
    "description": "Remove Line Breaks when copying from PDFs!",
    "background":{
        "scripts": ["text.js"],
        "persistent": false
    },
    "manifest_version": 2,
    "content_scripts": [
        {
            "matches": ["<all_urls>"],
            "js": ["ContentScript.js"]
        }
        ],
    "commands": {
        "copy" : {
            "suggested_key": {
                 "default": "Shift+Ctrl+X" 
            },
            "description": "Copy a text"
        }
    },
    "permissions": [
        "tabs",
        "background",
        "clipboardRead",
        "clipboardWrite"
      ]   
}

You can view the error in the console.

Aniket Das
  • 1
  • 1
  • 1
  • The built-in PDF viewer runs in an internal frame which must be bugged in regards to the clipboard API. Try using the classic document.execCommand + textarea to copy to clipboard. See also [How can I get selected text in pdf in Javascript?](https://stackoverflow.com/a/61076939) – wOxxOm Nov 14 '20 at 14:06
  • @wOxxOm thank you for the comment. I either need to get the selected text from the document or be able to read the clipboard contents. I can do neither right now in a PDF. I think the pdf_scripting_api should work, but I can't figure out how to use it within my extension. Can you link me to some pages which have examples of how to use the api? Thank you so much! – Aniket Das Nov 15 '20 at 19:57
  • See the answer I've linked. – wOxxOm Nov 15 '20 at 21:52
  • Does this answer your question? [Copy to clipboard from website when browser is not focused](https://stackoverflow.com/questions/59556207/copy-to-clipboard-from-website-when-browser-is-not-focused) – AncientSwordRage Nov 29 '21 at 10:58

0 Answers0