简体   繁体   中英

Allow keyboard shortcuts while limiting characters in iframe

I have an iframe which users can use to type and markup text with some html. I would however like to limit the amount of characters they can input.

To solve this I am using the following code:

iframeDocument.onkeypress=function(e){
 if(iframeDocument.body.textContent.length > 99 && e.keyCode != 8 && e.keyCode != 46 && e.keyCode != 40 && e.keyCode !=37 && e.keyCode != 38
 && e.keyCode !=39 && e.keyCode !=17){
 e.stopPropagation();
 e.preventDefault();
 return false;
 }}

This limits them to 100 characters while still allowing them to use markup without it affecting how many characters they can use. This method has two problems that I am having trouble solving.

  1. Keyboard shortcuts like ctrl+c and ctrl+v are disabled when the limit is reaching.
  2. Users are unable to highlight text and type another character to replace it when the limit is reached

How can I go about fixing these issues?

Even though you limit the user to enter only 100 characters he can still break it by disabling javascript. user can also edit the javascript or html with inspection tools. So this is not completely possible from client side. You have to validate on server side also. On your iframe you may have a textarea in that you can try this.

    <textarea onchange='this.value=(this.value.length<100)?this.value:"";' onkeypress='return (this.value.length<100);' >
    </textarea>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM