开发者

Detect pasted text with Ctrl+v or right click -> paste

开发者 https://www.devze.com 2023-01-06 02:14 出处:网络
Using JavaScript how do you to detect what text开发者_运维技巧 the user pastes into a textarea?You could use the paste event to detect the paste in most browsers (notably not Firefox 2 though). When y

Using JavaScript how do you to detect what text开发者_运维技巧 the user pastes into a textarea?


You could use the paste event to detect the paste in most browsers (notably not Firefox 2 though). When you handle the paste event, record the current selection, and then set a brief timer that calls a function after the paste has completed. This function can then compare lengths and to know where to look for the pasted content. Something like the following. For the sake of brevity, the function that gets the textarea selection does not work in IE. See here for something that does: How to get the start and end points of selection in text area?

function getTextAreaSelection(textarea) {
    var start = textarea.selectionStart, end = textarea.selectionEnd;
    return {
        start: start,
        end: end,
        length: end - start,
        text: textarea.value.slice(start, end)
    };
}

function detectPaste(textarea, callback) {
    textarea.onpaste = function() {
        var sel = getTextAreaSelection(textarea);
        var initialLength = textarea.value.length;
        window.setTimeout(function() {
            var val = textarea.value;
            var pastedTextLength = val.length - (initialLength - sel.length);
            var end = sel.start + pastedTextLength;
            callback({
                start: sel.start,
                end: end,
                length: pastedTextLength,
                text: val.slice(sel.start, end)
            });
        }, 1);
    };
}

var textarea = document.getElementById("your_textarea");
detectPaste(textarea, function(pasteInfo) {
    alert(pasteInfo.text);
    // pasteInfo also has properties for the start and end character
    // index and length of the pasted text
});


HTML5 already provides onpaste not only <input/> , but also editable elements (<p contenteditable="true" />, ...)

<input type="text" onpaste="myFunction()" value="Paste something in here">

More info here


Quite an old thread, but you might now use https://willemmulder.github.io/FilteredPaste.js/ instead. It will let you control what gets pasted into a textarea or contenteditable.


Works on IE 8 - 10

Creating custom code to enable the Paste command requires several steps.

  1. Set the event object returnValue to false in the onbeforepaste event to enable the Paste shortcut menu item.
  2. Cancel the default behavior of the client by setting the event object returnValue to false in the onpaste event handler. This applies only to objects, such as the text box, that have a default behavior defined for them.
  3. Specify a data format in which to paste the selection through the getData method of the clipboardData object.
  4. invoke the method in the onpaste event to execute custom paste code.

To invoke this event, do one of the following:

  • Right-click to display the shortcut menu and select Paste.
  • Or press CTRL+V.

Examples

<HEAD>
<SCRIPT>
var sNewString = "new content associated with this object";
var sSave = "";
// Selects the text that is to be cut.
function fnLoad() {
    var r = document.body.createTextRange();
    r.findText(oSource.innerText);
    r.select();
}
// Stores the text of the SPAN in a variable that is set 
// to an empty string in the variable declaration above.
function fnBeforeCut() {
    sSave = oSource.innerText;
    event.returnValue = false;
}
// Associates the variable sNewString with the text being cut.
function fnCut() {
    window.clipboardData.setData("Text", sNewString);
}
function fnBeforePaste() {
    event.returnValue = false;
}
// The second parameter set in getData causes sNewString 
// to be pasted into the text input. Passing no second
// parameter causes the SPAN text to be pasted instead.
function fnPaste() {
    event.returnValue = false;
    oTarget.value = window.clipboardData.getData("Text", sNewString);
}
</SCRIPT>
</HEAD>
<BODY onload="fnLoad()">
<SPAN ID="oSource" 
      onbeforecut="fnBeforeCut()" 
      oncut="fnCut()">Cut this Text</SPAN>
<INPUT ID="oTarget" TYPE="text" VALUE="Paste the Text Here"
      onbeforepaste="fnBeforePaste()" 
      onpaste="fnPaste()">
</BODY>

Full doc: http://msdn.microsoft.com/en-us/library/ie/ms536955(v=vs.85).aspx


I like the suggestion for the right click

$("#message").on('keyup contextmenu input', function(event) { 
  alert("ok");
});

finded here:

Source: Fire event with right mouse click and Paste


Following may help you

  function submitenter(myfield,e)
  {
    var keycode;
    if (window.event) keycode = window.event.keyCode;
    else if (e) keycode = e.which;
    else return true;
    if (keycode == //event code of ctrl-v)
    {
      //some code here
    }

  }

  <teaxtarea name="area[name]" onKeyPress=>"return submitenter(this,event);"></textarea> 


The input event fires when the value of an , , or element has been changed.

const element = document.getElementById("input_element_id");
element.addEventListener('input', e => {
// insertText or insertFromPaste
   if(inputType === "insertFromPaste"){
       console.log("This text is copied");
   }
   if(inputType === "insertText"){
       console.log("This text is typed");
   }


})


You could either use html5 oninput attribute or jquery input event

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
  $("body").on('input','#myinp',function(){
 $("span").css("display", "inline").fadeOut(2000);
  });
</script>
<style>
span {
  display: none;
}
</style>
</head>
<body>

<input id="myinp" type="search" onclick="this.select()" autocomplete="off" placeholder="paste here">

<span>Nice to meet you!</span>

</body>
</html>

0

精彩评论

暂无评论...
验证码 换一张
取 消