Is it possible to programmatically alter the clipboard using Javascript without requiring any user interaction?

I'm developing a script to simplify the reformatting of copied text, specifically phone numbers. I aim to paste the text into a textbox and have the formatted output automatically copied to my clipboard to reduce manual efforts.

The function for updating the clipboard only triggers with a genuine click event. I've tried multiple methods like programmatically invoking .click(), dispatching a "click" event, using async/await, and promises

JSFiddle Code: https://jsfiddle.net/ByteBender/7bukf5xh/9/

document.getElementById('myInput').addEventListener('paste', event => {
    const contents = event.clipboardData.getData('text')
    if (contents.length >= 9) {
        event.preventDefault()
        const formattedNumber = formatPhoneNumber(contents)
        myInput.value = formattedNumber
        copyToClipboard()
        
      // Also failed to copy
      //myButton.click()
      // Also failed to copy
      //setTimeout( () => myButton.dispatchEvent(new Event('click')), 500 )
    }
});

function copyToClipboard() {
  var copyText = document.getElementById("myInput");
  copyText.select();
  copyText.setSelectionRange(0, 99999); // For mobile devices
  navigator.clipboard.writeText(copyText.value)
    .then(()=> console.log('success!'))
    .catch(err=>console.error(`fail: ${err}`))
}


// Also failed to copy
/* function tempButton(){
  var button = document.createElement('button');
  button.innerHTML = 'click me';
  button.onclick = function(){
    copyToClipboard();
        return false;
  };
  document.body.appendChild(button);
  //button.click()
  
} */

Answer №1

For Chrome/Chromium browsers, I believe this code should function without any modifications. However, for Firefox, you will need to implement transient activation.

To address this issue in Firefox as a workaround, you can use the window.addEventListener() method to listen for all possible transient-activation events and then utilize the clipboard API accordingly.

clipboardFunc = () => { 
  navigator.clipboard.writeText("hello");
  console.log("Copied to clipboard! Removing self.");
  removeClipboardFunc();
}

removeClipboardFunc = () => {
  window.removeEventListener("keydown", clipboardFunc);
}

window.addEventListener("keydown", clipboardFunc);

It's worth considering whether it is ethically sound to circumvent these security measures and potentially go against the user's intentions by manipulating the clipboard contents. What if someone had something important saved on their clipboard?

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

Validating dynamic textboxes in Angular with custom rules

Creating dynamic textboxes with *ngFor in Angular <tr *ngFor="let computer in _Computers; let i = index;"> <td>{{computer.Name}}</td><td>{{computer.Optional}}</td> <td> <input matInput [formControl] = " ...

Troubleshooting: Issues with window.location.href and window.open within an iframe

Code Update <div> <button type="button" class="submit btn btn-default" id="btnSubmit">Submit </button> <button type="button">Cancel</button> </div> <script> $("#btnSubmit").click(function(e) { ...

Issue: Database not updating after input via AJAXExplanation: Despite submitting new data through AJAX, the

I've been struggling to display the UPDATED database on my initial html page after submitting new information. Despite successfully updating the database using AJAX, I can only see the outdated version. Any assistance in resolving this issue would be ...

Initiate an AJAX request to the server upon beforeunload event

It seems that starting with Firefox version 4, binding the window jQuery object to beforeunload is no longer effective. I want to send an AJAX post request to delete data from my server's memcache. When I refresh the only open tab, I can observe tha ...

What is the reason for the continual influx of new users being added to the database?

I have a Node.JS and MongoDB console application where I've implemented adding users in one file and outputting all collection objects to the console in another file. When running the command - node scripts/get_all_users.js, both existing users are di ...

Determining the necessary data to send via ajax for a particular issue

Currently, I am learning JavaScript and have encountered another challenge along the way. I am looking for assistance in understanding the concept, whether it is a solution in jQuery or Angular. I have two types of tasks in my HTML - audio or graphic. The ...

I'm looking to filter this array based on the value of a subarray that the user will specify the key and value for. How can I accomplish

Given the input var key="value_0" and var input="hello", I need to filter the array in TypeScript based on these values. The filtering criteria involve checking if the array elements contain a subarray with key="value_0" and if the value of this key includ ...

showing a fading-in effect after a successful AJAX post

Maybe a simple question, but I've been struggling to make this work for quite some time now. Despite trying various solutions from stackoverflow, I can't seem to get it right. Perhaps fresh eyes could help me figure out how to achieve this. My g ...

JavaScript code to locate the most pertinent strings within an array based on a specific substring

I'm working with a large array containing names of people, such as: let names = [ "John Brown", "Tristan Black", "Carl Jobbs", "Aidan Burrows", "Taylor Joe" ]; When given an input, I want to return the top 5 most relevant results ...

Can HTML5 and JavaScript be used to clip a portion of a video and upload it directly to a server?

Currently, I am using Filereader to read a local video file (mp4) in order to display it in a video tag. However, I am looking to cut a specific part of the mp4 file (for example, from 5 to 10 seconds) and then upload it to a server. My current approach: ...

The Ajax request is successfully looping through multiple files, however, it is not properly sending them to the server. As a result, only one file

I have been working on an ajax request that successfully retrieves information about files, such as the number of files, their names, and looping through them. Now, I am faced with the challenge of saving these files to a local folder on my computer. I hav ...

Update the chat <div> automatically whenever a new message is added to the MySQL database

I have been looking online for a code that can update the chat <div> every time a new message is received from the other user. I have come across mentions of setTimeout() and setInterval(), but I would appreciate advice and assistance from more exper ...

Should Errors be Handled in the Service Layer or the Controller in the MVC Model?

Currently, I am in the process of developing a Backend using Express and following the MVC Model. However, I am uncertain about where to handle errors effectively. I have integrated express-async-errors and http-errors, allowing me to throw Errors anywher ...

What is the best way to incorporate TypeScript into a simple JavaScript project and release it as a JavaScript library with JSDoc for TypeScript users?

Issue: I have encountered difficulties finding an efficient solution for this. Here's a summary of what I attempted: To start, ensure that allowJs and checkJs are both set to true in the tsconfig.json, then include the project files accordingly. Ty ...

Videos embedded using the React HTML video tag are not automatically playing on mobile devices

I have implemented a jsx variable to insert a video into my html. Despite following the advice to include muted defaultMuted, and playsinline (which I have already done), the videos autoplay on safari, chrome, and firefox on my computer but not on mobile ...

Creating real-time chat using Node.js

I am looking to create a live chat feature using node js. Can someone provide guidance on how to achieve this? Here are the use cases I have determined: Users will have the option to click on a link or icon labeled 'Online chat support' on the ...

Locate a jquery element that is within a parent element containing specific text

This is the format I currently have: <td width="270px"> <img class="bullet" border="0" valign="top" src="gray-bullet.gif"> this is the text </td> Can someone provide me with a query to specifically target the img element with the class ...

Personalizing navigation tabs using Bootstrap

I've been working on creating a custom bootstrap navbar tabs, but I'm struggling to remove the borders and apply the custom colors. After some trial and error, here's what I have so far: .nav-tabs, .nav-pills { text-align: center; bo ...

The promise is only guaranteed to resolve correctly upon the refreshing of the page

Exploring an API that retrieves a list of Pokemon and related data, the code snippet below demonstrates how to achieve this. export function SomePage() { const [arr, setArray] = useState([]); useEffect(() => { fetchSomePokemon(); }, []); f ...

Safari browser cutting off POST parameters prematurely

I am encountering an issue where my code works perfectly on all browsers except Safari 6.1.2 on Mac OS Lion. Below is the AJAX post code that I am using - $.ajax({ type: 'POST', dataType: 'text/html', url:"/MyProxy.php ...