Programster's Blog

Tutorials focusing on Linux, programming, and open-source

HTML5 - Context Menus

Context menu was a great idea, but unfortunately it never got adopted and Firefox themselves dropped support for it. I am leaving this post just in case it comes in handy later for whatever reason of if I find an HTML5 alternative.

Original Post

One of the great additions in HTML5 was the ability to add to the context menu when the user right clicks something. Not all browsers support this (such as Chromium and Opera), but it will work in Firefox.

Below is a code example which will use a context menu to copy to clipboard, which itself can be right clicked for the option menu to copy to clipboard.

<pre id="code-to-copy" contextmenu="menu">
// This is some code
// Another line

var copyCodeFunction = function(event)
    // Select the email link anchor text  
    var emailLink = document.querySelector('#code-to-copy');
    var range = document.createRange();

        // Now that we've selected the anchor text, execute the copy command
        var successful = document.execCommand('copy');
        var msg = successful ? 'successful' : 'unsuccessful';
        console.log('Copy email command was ' + msg);
    catch (err)
        console.log('Oops, unable to copy');

    // Remove the selections - NOTE: Should use
    // removeRange(range) when it is supported


<!-- Add the right click context menu to copy code -->
<menu type="context" id="menu">
    <menuitem label="Copy To Clipboard" onCLick="copyCodeFunction();"></menuitem>

Last updated: 7th May 2023
First published: 16th August 2018