How To Run The Ctrl+D Shortcut On JavaScript Button Click

Viewed 27

Is it possible to call the Ctrl+D shortcut using JavaScript button click?

I want to add a "Add To Bookmark" button on my custom context menu for my website, for that I want a function that calls the "Ctrl+D" shortcut on a button click to show the browser's default "Add to Bookmark/ Favourites" dialog box.

I have tried many pre available solutions from internet but none of them is working for me.

let bookmark = document.querySelector('.bookmark');

bookmark.addEventListener('click', ()=> {
  // Call The "Ctrl+D" Shortcut!
});
<button type="button" class="bookmark">Bookmark</button>

1 Answers

You can simulate keypress events using JavaScript.. but I'm not sure this will work as per your need

Give it a try

window.dispatchEvent(new KeyboardEvent('keydown', {
        key: "d",
        ctrlKey: true,
        bubbles: false,
        metaKey: false   
    })
);

For more details visit here

Related