admin管理员组

文章数量:1336204

I am a fresher and working on a Coupons website.

I want to know, when a window loads, how to press Ctrl+C itself.

Ctrl+C keys should be pressed automatically right after the loading of window.

I am a fresher and working on a Coupons website.

I want to know, when a window loads, how to press Ctrl+C itself.

Ctrl+C keys should be pressed automatically right after the loading of window.

Share Improve this question edited Sep 24, 2024 at 17:36 m-sarabi 2,3051 gold badge16 silver badges24 bronze badges asked Feb 2, 2017 at 17:02 user7507073user7507073 191 silver badge3 bronze badges 8
  • 1 Why not just perform the action that the CTRL+C key should perform with: document.execCommand("copy") – Scott Marcus Commented Feb 2, 2017 at 17:04
  • @ScottMarcus Not copy but ctrl+c. It just the start, there are lots of other plex things there and only ctrl+c would work there as my Team Leader told me. – user7507073 Commented Feb 2, 2017 at 17:06
  • @user7507073 CTRL+C is the operating system mand for copy. But, my answer would still be the same. Just call the functions that initiate the "lots of other plex things". The key presses aren't necessary. – Scott Marcus Commented Feb 2, 2017 at 17:08
  • @ScottMarcus Alright dear, thank you! But, isn't there any way to do so? Your help will be highly appreciated. – user7507073 Commented Feb 2, 2017 at 17:11
  • Possible duplicate of How to simulate keypress using Javascript? – Teemu Commented Feb 2, 2017 at 17:20
 |  Show 3 more ments

1 Answer 1

Reset to default 8

Working fiddle.

Since you're using jQuery you could do it using jQuery.Event :

var e = jQuery.Event("keydown");

e.which = 67; // 'C' key code value
e.ctrlKey = true;

$("body").trigger(e);

Hope this helps.

jQuery Solution

$(function(){ //Ready function
  
  //Event that catch the Ctrl+C press (Just for test)
  $("body").keydown(function(e) {
    var code = (e.keyCode ? e.keyCode : e.which);

    if (code == 67) {
      if (e.ctrlKey) {
        alert("Ctrl+C was pressed!!");
      }
    }
  });

  //Event that trigger the 'Ctrl+C' 
  var e = jQuery.Event("keydown");
  
  e.which = 67; // 'C' key code value
  e.ctrlKey = true;
  
  $("body").trigger(e);
})
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Javascript Solution

document.addEventListener('keydown', function (e) {
  if (event.altKey && event.key === 'n') 
  {
    document.querySelectorAll('._180aQody._254QuS8h')[0].click();
  }
});

document.querySelector('._180aQody._254QuS8h').addEventListener('click', function (e) {
  alert("Alt+n was pressed!!");
});

var ev = new KeyboardEvent('keydown', {bubbles: true,  altKey: true,  key: "n"});
document.querySelectorAll('._180aQody._254QuS8h')[0].dispatchEvent(ev);
<button class='_180aQody _254QuS8h'>CLick me using Alt+n</button>

本文标签: javascriptPress Ctrlc keys automatically onloadStack Overflow