Why is it that the document.execCommand("copy") function is not functioning within the content script of my chrome extension?

I am trying to implement a feature in my Chrome extension where I can write data to the clipboard. I have already specified permissions for clipboardRead and clipboardWrite in the manifest file.

I came across a function that I thought would work, which I found here. However, it seems that the line "document.execCommand('copy');" is not functioning as expected.

All of this code is written in the content script.

Thanks, manifest:

{
    "manifest_version":2,

    "name":"easyCopy",
    "description":"just a small tool",
    "version":"1.0.0",

    "permissions":[
        "clipboardWrite", "http://*/*", "clipboardRead"
    ],

    "content_scripts":[
        {
            "matches":["http://*/*"],
            "js":["jquery-1.9.1.min.js", "main_feature.js"]
        }
    ],

    "background":{
        "persistent":false,
        "page":"background.html"
    }
}

main_feature.js:

copyOrderId();
function copyOrderId() {
    $(".order-num").click(function () {
        var curOrderNum = $(this).text();
        copyTextToClipboard(curOrderNum);
//        chrome.extension.sendMessage({method:"copy", content:curOrderNum}, function (response) {
//            clog(response);
//        });
    });


}

function copyTextToClipboard(text) {
    var copyFrom = $('<textarea/>');
    copyFrom.text(text);
    $('body').append(copyFrom);
    copyFrom.select();
    document.execCommand('copy', true);
    copyFrom.remove();

}
function clog(message) {
    console.log(message);
}

the background.html is just a blank page with basic html body.

Answer №1

Many thanks to all for the help, I ultimately ended up implementing this solution:

document.execCommand is unable to function within a content script. Instead, data is sent to the background page where the "copyTextToClipboard" function is executed.

It's important to note that your JavaScript should be placed in a single .js file rather than being mixed with background.html.

Furthermore, the textarea must possess either an id or class property.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is the $scope object shared among all controllers in AngularJS when nested controllers are used?

Is it possible to use nested controllers in AngularJS? When using nested controllers, is the $scope object shared across all controllers? The issue at hand is:- While I can access the $scope values of the first controller across all controllers, I am una ...

Sending information from one page to another and then sending it once more

I am currently utilizing the following code to submit a form's data to : <script type="text/javascript"> $(document).ready(function(){ $("#textnextofkin").validate({ debug: false, rules: { ...

Is there a way to remove this specific element from an inherited hyperlink?

My website can be found at whensayfeed.meteor.com. Each post on the site is enclosed within an <a></a> element. The heart symbol on the right side of each post is intended to be a "like button" that users can click on. However, because it is ...

Challenge of managing transactions involving both the setTimeout function and user clicks

My slider is experiencing a conflict when I click on the links to go to each slider before finishing the transition. It seems to work smoothly only if I click after the transition. Check out my jsfiddle here This slider is built using jQuery. var curren ...

Request made to Ajax fetching complete webpage content

I have a page full of random tips at http://www.javaexperience.com/tips To display these tips on other pages of the website, I am using an ajax call to add the content returned by the call to a specific div's HTML. The code for the div is: <div ...

Formatting database values in `where` conditions for strings in TypeORM: A simple guide

I am trying to utilize TypeORM's "exist" method in order to check if a name has already been inserted into the database. My issue is that I cannot determine whether the name was inserted in uppercase or lowercase, leading to potential false validatio ...

In a Custom Next.js App component, React props do not cascade down

I recently developed a custom next.js App component as a class with the purpose of overriding the componentDidMount function to initialize Google Analytics. class MyApp extends App { async componentDidMount(): Promise<void> { await initia ...

combine several arrays next to each other based on a specified key

I have a collection of three sets, each containing three elements: Set1 = [[apple, 2, 4], [banana, 5, 5], [cherry, 4, 1]] Set2 = [[banana, 1, 7], [cherry, 3, 8], [date, 5, 4]] Set3 = [[apple, 5, 2], [banana, 0, 9], ...

How to retrieve the id for Inline Editing of Textarea?

I utilize jqInlineEdit for implementing inline editing functionality on my website. While everything else is functioning correctly, I am facing difficulty in retrieving the id of the item required for saving changes to the database (using Django). The str ...

What is the necessity of explicitly requesting certain core modules in Node.js?

The documentation explains that certain core modules are included in the Node.js platform itself and are specified within the source code. The terminology can get a bit confusing when it comes to details. The term "global objects" (or standard built-in obj ...

Is there a way to transmit data to another page upon clicking a button?

Greetings! As I work on developing an ASP.NET JavaScript application in SharePoint, I encounter a specific issue. My project consists of two pages: default.aspx and addnewitem.aspx. On the default.aspx page, there is a gridview with an edit button. Ideally ...

What is the best way to incorporate objHoles into every individual object?

I need to assign specific attributes to each player in a game. Each player should have different sets of holes, with each hole having its own win, lose, push, and points values ranging from 0-20. Is there a simple way to accomplish this task? As a beginn ...

Triggering onClick events on list items to update text fields

I have been attempting to create an onClick event for li items. The goal is to change some specified text in a div to preset text using JavaScript whenever this event is activated. However, I have been unsuccessful so far. I even tried reaching out for hel ...

Using Javascript to Change Background Color on Button Click

The button press does not result in a change of the background color. What could be causing this issue? var body = document.getElementsByTagName("body"); var bgbutton = doucument.getElementById("bgchange"); bgbutton.onclick = function() { body.style.b ...

Load a CodeIgniter view using Ajax technology

Greetings! I am currently developing an application using CodeIgniter and facing an issue with dynamically loading page content via AJAX. This is how I am attempting to achieve it: $.ajax({ url:'/customer/customerList', type: 'POST& ...

Remove letters at random from a string

Looking to randomly remove 3 letters from a string. Tried using the substr() or slice() function but struggling to choose random letters to remove. Check out my current demo below: http://jsfiddle.net/euuhyfr4/ If anyone has any suggestions, I'd g ...

What is the purpose of using CORS with Express?

Here is how my express server setup looks: const cors = require('cors'); const express = require('express'); const app = express(); const port = 8000; app.use(cors({origin: 'http://localhost:8000'})); // Handle requests of c ...

Using webpack to load the css dependency of a requirejs module

Working with webpack and needing to incorporate libraries designed for requirejs has been smooth sailing so far. However, a bump in the road appeared when one of the libraries introduced a css dependency: define(["css!./stylesheet.css"], function(){ &bsol ...

Quickest technique to verify a specific telephone number format

Our task is to identify if a given string matches a specific phone number pattern. This pattern consists of three sets of digits separated by hyphens: ddd-ddd-dddd. The patterns currently being tested are: "012-345-6789" "0124-345-6789" "012-3456-6789" " ...

What steps can be taken to ensure that the onchange event functions properly with radio input

I am facing an issue with my input field as the value changes automatically when an option is selected. However, I want this functionality to also work the same way when a radio input option is selected. How can I modify the code to achieve this? func ...