How to capture keys inside an iframe

Asked

Viewed 89 times

1

I am making a javascript text editor and need to create keyboard shortcuts to perform some actions. for this, I am using CDEditorIframe.document.body.setAttribute('onkeypress', 'teste()'); The error is where I try to put some function (like the teste()) to handle the keys and all decision structures, where the console returns

 Uncaught ReferenceError: teste is not defined
    at HTMLBodyElement.onkeypress (about:blank:1)

function initIframe() {

  CDEditorIframe.document.body.style.wordWrap = 'break-word';
  CDEditorIframe.document.body.style.margin = 0;
  CDEditorIframe.document.designMode = 'on';

  CDEditorIframe.document.body.setAttribute('onkeypress', 'teste()');

}

function executar_comando(command, showWUI, value) {
  CDEditorIframe.document.execCommand(command, showWUI, value);
}

function teste() {
  console.log("união flasco");
}
.cd-editor {
  background-color: #d4d4d4;
  box-sizing: border-box;
  width: 100%;
  min-height: 600px;
  margin: 0;
  padding: 10px;
  border: 0;
  display: block;
  overflow: auto;
  border: 1px solid #999;
  border-top: none;
  border-bottom-left-radius: 4px;
  border-bottom-right-radius: 4px;
}

.cores:hover {
  background-color: #d4d4d4;
}
<!DOCTYPE html>
<html>

<head>
  <title>Editor de texto</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

  <!-- Bootstrap CSS -->
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
  <link rel="stylesheet" href="editor.css">

  <script src="https://kit.fontawesome.com/6d286bc5d2.js" crossorigin="anonymous"></script>
  <script src="main.js"></script>
</head>

<body style="background-color:#464642;" onload="initIframe();">

  <div class="wrapper">

    <div class="container-fluid" style="max-width: 75%; margin-top: 5%;padding: 0; background-color: #eaa3a3;">

      <nav class="nav justify-content-center">
        <div class="dropdown">
          <a class="nav-link dropdown-toggle" data-toggle="dropdown" href="#" role="button" aria-haspopup="true">Fontes</a>
          <div class="dropdown-menu">
            <a class="dropdown-item cores" href="#" onclick="executar_comando('fontName', 'false', 'Times New Roman')">Padrão</a>
            <div class="dropdown-divider"></div>
            <a class="dropdown-item cores" href="#" onclick="executar_comando('fontName', 'false', 'Arial')">Arial</a>
            <a class="dropdown-item cores" href="#" onclick="executar_comando('fontName', 'false', 'Calibri')">Calibri</a>
            <a class="dropdown-item cores" href="#" onclick="executar_comando('fontName', 'false', 'Comic Sans MS')">Comic Sans MS</a>
            <a class="dropdown-item cores" href="#" onclick="executar_comando('fontName', 'false', 'Impact')">Impact</a>
            <a class="dropdown-item cores" href="#" onclick="executar_comando('fontName', 'false', 'Trebuchet MS')">Trebuchet MS</a>
          </div>
        </div>

        <div class="dropdown">
          <a class="nav-link dropdown-toggle" data-toggle="dropdown" href="#" role="button" aria-haspopup="true" aria-expanded="false">Tamanho</a>
          <div class="dropdown-menu">
            <a class="dropdown-item cores" href="#" onclick="executar_comando('fontsize', 'false', '1')">1</a>
            <a class="dropdown-item cores" href="#" onclick="executar_comando('fontSize', 'false', '2')">2</a>
            <a class="dropdown-item cores" href="#" onclick="executar_comando('fontSize', 'false', '3')">3</a>
            <a class="dropdown-item cores" href="#" onclick="executar_comando('fontSize', 'false', '4')">4</a>
            <a class="dropdown-item cores" href="#" onclick="executar_comando('fontSize', 'false', '5')">5</a>
            <a class="dropdown-item cores" href="#" onclick="executar_comando('fontSize', 'false', '6')">6</a>
            <a class="dropdown-item cores" href="#" onclick="executar_comando('fontSize', 'false', '7')">7</a>
          </div>
        </div>

        <div class="border border-dark" style="margin-left: 2%; margin-right: 2%;"></div>

        <a class="nav-link" href="#" title="Negrito" onclick="executar_comando('bold', 'false', 'null');"><i class="fas fa-bold"></i></a>
        <a class="nav-link" href="#" title="Itálico" onclick="executar_comando('italic', 'false', 'null');"><i class="fas fa-italic"></i></a>
        <a class="nav-link" href="#" title="Sublinhado" onclick="executar_comando('underline', 'false', 'null');"><i class="fa fa-underline"></i></a>
        <a class="nav-link" href="#" title="Cortado" onclick="executar_comando('strikethrough', 'false', 'null');"><i class="fa fa-strikethrough"></i></a>


        <div class="border border-dark" style="margin-left: 2%; margin-right: 2%;"></div>


        <a class="nav-link" href="#" title="Alinhamento à esquerda" onclick="executar_comando('justifyLeft', 'false', 'null');"><i class="fas fa-align-left"></i></a>
        <a class="nav-link" href="#" title="Alinhamento ao centro" onclick="executar_comando('justifyCenter', 'false', 'null');"><i class="fas fa-align-center"></i></a>
        <a class="nav-link" href="#" title="Alinhamento justificado" onclick="executar_comando('justifyFull', 'false', 'null');"><i class="fas fa-align-justify"></i></a>
        <a class="nav-link" href="#" title="Alinhamento à direita" onclick="executar_comando('justifyRight', 'false', 'null');"><i class="fas fa-align-right"></i></a>

        <div class="border border-dark" style="margin-left: 2%; margin-right: 2%;"></div>


        <div class="dropdown ">
          <a class="nav-link dropdown-toggle" data-toggle="dropdown" href="#" role="button" aria-haspopup="true" aria-expanded="false">Cor da Fonte</a>
          <div class="dropdown-menu">
            <a class="dropdown-item cores" href="#" onclick="executar_comando('foreColor', 'false', 'black')" style="color: black;">Preto</a>
            <a class="dropdown-item cores" href="#" onclick="executar_comando('foreColor', 'false', 'blue')" style="color: blue;">Azul</a>
            <a class="dropdown-item cores" href="#" onclick="executar_comando('foreColor', 'false', 'red')" style="color: red;">Vermelho</a>
            <a class="dropdown-item cores" href="#" onclick="executar_comando('foreColor', 'false', 'pink')" style="color: pink;">Rosa</a>
            <a class="dropdown-item cores" href="#" onclick="executar_comando('foreColor', 'false', 'purple')" style="color: purple;">Roxo</a>
            <a class="dropdown-item cores" href="#" onclick="executar_comando('foreColor', 'false', 'green')" style="color: green;">Verde</a>
          </div>
        </div>



        <div class="border border-dark" style="margin-left: 2%; margin-right: 2%;"></div>


        <a class="nav-link" href="#" title="Lista" onclick="executar_comando('insertUnorderedList', 'false', 'null');"><i class="fa fa-list"></i></a>
        <a class="nav-link" href="#" title="Lista Ordenada" onclick="executar_comando('insertOrderedList', 'false', 'null');"><i class="fa fa-list-ol"></i></a>
        <a class="nav-link" href="#" title="Identar" onclick="executar_comando('indent', 'false', 'null');"><i class="fa fa-indent"></i></a>
        <a class="nav-link" href="#" title="Tirar Identação" onclick="executar_comando('outdent', 'false', 'null');"><i class="fa fa-outdent"></i></a>

        <div class="border border-dark" style="margin-left: 2%; margin-right: 2%;"></div>

        <a class="nav-link" href="#" title="Lista" onclick="executar_comando('insertImage', 'false', prompt('Insira a URL de uma imagem:', ''))"><i class=" fa fa-file-image-o"></i></a>


      </nav>

      <form>
        <div class="form-group">
          <iframe o class="cd-editor" name="CDEditorIframe" id="CDEditorIframe"></iframe>
        </div>
      </form>

    </div>

  </div>


  <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>


</body>

</html>

1 answer

2


The function teste() is in the main document where the iframe is, and how you placed the event calling the function in the body iframe, the event does not find the function, so it gives this error, because the function teste() does not exist inside the iframe.

To call the function from the iframe, you must use window.parent, referencing the iframe parent document:

CDEditorIframe.document.body.setAttribute('onkeypress', 'window.parent.teste()');

Just remembering that this will only work if the function teste() has overall scope in the parent document.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.