Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / ASP.NET

How to copy-protect a page using JavaScript in ASP.NET

1.92/5 (5 votes)
20 Nov 2011CPOL 15.9K  
How to protect a page from text copying using JavaScript in ASP.NET.
Quote: Many of the time we don’t want to let the user copy our page for some security reason. In my company I have to design a website for textile engineers where they can submit their article and they don’t want to let the non register user to copy their article from the page.

Here is an example of how I have done it. For this I have used JavaScript in my ASP.NET project.


Open your Project, go to your desired .aspx page, and copy the following JavaScript code in the Head section. Here I have created two types of functions to protect both from mouse and keyboard.


JavaScript
<script type="text/javascript">
    function noCopyMouse(e) {
        var isRight = (e.button) ? (e.button == 2) : (e.which == 3);

        if(isRight) {
            alert('This page is copy protected');
            return false;
        }
        return true;
    }

    function noCopyKey(e) {
        var forbiddenKeys = new Array('c','x','v');
        var keyCode = (e.keyCode) ? e.keyCode : e.which;
        var isCtrl;

        if(window.event)
            isCtrl = e.ctrlKey
        else
            isCtrl = (window.Event) ? ((e.modifiers & 
                        Event.CTRL_MASK) == Event.CTRL_MASK) : false;

        if(isCtrl) {
            for(i = 0; i < forbiddenKeys.length; i++) {
                if(forbiddenKeys[i] == String.fromCharCode(keyCode).toLowerCase()) {
                    alert('This page is copy protected');
                    return false;
                }
            }
        }
        return true;
    }
</script>

Now you have to select which part in your page you don’t want to copy. Here I don’t want to let copy my entire page so I use a panel and create all my tables in the panel.


XML
<asp:Panel ID="Panel1" runat="server">
       <table cellpadding="0" cellspacing="0" width="100%">
           <tr>
               <td>
                   <asp:Label ID="Label5" runat="server" 
                       Text="Try to copy me."></asp:Label>
               </td>
           </tr>
       </table>
   </asp:Panel>

Now go to your .cs page and write the following code in the Load event.


C#
protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        Panel1.Attributes.Add("onmousedown", "return noCopyMouse(event);");
        Panel1.Attributes.Add("onkeydown", "return noCopyKey(event);");
    }
}

Run your project, select some text from the page, and try to copy it, a warning message will be shown.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)