3

I needed at some point to fill a div with the values of the keystrokes being pressed. I thought that the following code would work:

new Vue({
  el: "#app",
  data: {
    content: ""
  },
  methods: {
    press: function(event) {
      console.log(event.key)
      this.content += event.key
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <div v-on:keyup="press">
    click here and type {{content}}
  </div>
</div>

Is there something specific to be done to catch keystrokes in a browser when the window is active (but there are no input elements)?

WoJ
  • 27,165
  • 48
  • 180
  • 345
  • Why not simply using an input instead? – Federico klez Culloca Mar 14 '19 at 11:45
  • @FedericoklezCulloca: this is for a very specific case which demonstrates [clickjacking](https://www.owasp.org/index.php/Clickjacking) and such functionality would have come in handy. This is absolutely not for "normal" applications. – WoJ Mar 14 '19 at 11:47
  • Here's a non-vue specific js example capturing the onkeydown event on the document. https://stackoverflow.com/a/2880614/3585500 – ourmandave Mar 14 '19 at 11:48

1 Answers1

0

Use contenteditable div attribute

new Vue({
  el: "#app",
  data: {
    content: ""
  },
  methods: {
    press: function(event) {
      this.content = event.target.innerText
      console.log('key:', event.key )
    }
  }
})
.view {color: red }
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <div @keyup="press" contenteditable="true">type here</div>
  
  <div class="view">{{content}}</div>
</div>
Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345
  • Please see my comment on Vucko's answer which is the same as yours I believe. – WoJ Mar 14 '19 at 12:07
  • *IFRAME case is separate question* I do not understand you comment? My question is not about IFRAMEs (they are just the context which I did not even brought up in my question to focus on the actual need) – WoJ Mar 14 '19 at 12:08