Thomas Cheney
Thomas Cheney

Reputation: 388

Javascript DOM send value to function embedded in iframe to simulate keypress

I have a test that I have been working on, trying to send a value to a function defined within an iframe (both pages from the same source). The content of the iframe when in focus responds to certain keystrokes. What I would like to achieve is triggering those keypress actions from the iframe by means of a button on the primary page.

The content of the iframe is dynamic, and needs to function without refreshing, otherwise I know I could change the iframe src to carry the variables. What I have so far...

Parent Page:

<!DOCTYPE html><html><head>
<style>
  iframe{border:1px solid blue;height:100px;width:100px;margin:20px auto 0 auto;}
</style>
</head><body>
<iframe id="iframe" src="iframetest2.html"></iframe>
<button onclick="simKey(32);">CLICK</button>
<script>
  var iframe=document.getElementById('iframe');
  var ifContent=iframe.contentWindow
  function simKey(x){
    ifContent.postMessage(testScript(x),'*','[transfer]');
  }
</script></body></html>

And the iFrame content:

<!DOCTYPE html><html><head>
<script>
  function testScript(x){
document.body.innerHTML=x;
setTimeout(function(){document.body.innerHTML='';},700);
  }
  </script></head><body onkeypress="testScript(event.keyCode)"></body></html>

I am also trying to avoid the use of jQuery if possible. This is a concept web design, and really want to hand-write the Javascript so that I can modify as need be.

Upvotes: 1

Views: 2587

Answers (1)

m59
m59

Reputation: 43755

First, inline js (like onkeypress in your html) is a bad practice. Read some these results: https://www.google.com/search?q=Why+is+inline+js+bad%3F

I will be using the best practice addEventListener.

Fire iFrame keypress event from button on parent window:

Live demo (click).

Main Page:

var myBtn = document.getElementById('myBtn');
var iframe = document.getElementById('myIframe');

myBtn.addEventListener('click', function() {
  var evt = new Event('keypress');
  evt.keyCode = '115';
  iframe.contentDocument.body.dispatchEvent(evt);
});

iFrame:

document.body.addEventListener('keypress', function(e) {
  console.log(e.keyCode);
});

Here are some docs that might help you if you need to support older browsers or want more information: https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Creating_and_triggering_events

Old Answer: this listens to keypresses on the parent window.

In the iFrame, you just need to have this JavaScript:

window.parent.document.body.addEventListener('keypress', function(e) {
  console.log(e.keyCode);
});

Upvotes: 3

Related Questions