来自iFrame的自动保存(localStorage)文本字段不起作用

时间:2014-03-15 20:40:46

标签: javascript html5 iframe local-storage autosave

我正在构建一个富文本编辑器,并希望在iframe中自动保存文本。 我有多个代码部分和片段 - 单独使用 - 工作正常,但我无法正确组装它们。 LIVEDEMO

以下是我想要实现的图片:Editor Structure

我有一个可编辑的iFrame,这是我的文本编辑器。此iFrame的innerHTML应加载到隐藏在iframe下的textarea中,textarea的内容应定期保存在localStorage中。

iFrame代码有效。

<script>

  function iFrameOn() {
    richTextField.document.designMode = 'On';
  }

  function iBold() {
    richTextField.document.execCommand('bold', false, null);
  }

  function iUnderline() {
    richTextField.document.execCommand('underline', false, null);
  }

  function iItalic() {
    richTextField.document.execCommand('italic', false, null);
  }

  function iFontSize() {
    var size = prompt('Enter a size 1-7', '')
    richTextField.document.execCommand('FontSize', false, size);
  }

  function iForeColor() {
    var color = prompt('Define a basic color or apply a hexadecimal color code for advanced colors:', '')
    richTextField.document.execCommand('ForeColor', false, color);
  }

  function iHorizontalRule() {
    richTextField.document.execCommand('InsertHorizontalRule', false, null);
  }

  function iUnorderedList() {
    richTextField.document.execCommand('InsertUnorderedList', false, "newUL");
  }

  function iOrderedList() {
    richTextField.document.execCommand('InsertOrderedList', false, "newOL");
  }

  function iLink() {
    var linkURL = prompt('Enter the URL for this link:', 'http://')
    richTextField.document.execCommand('CreateLink', false, linkURL);
  }

  function iUnLink() {
    richTextField.document.execCommand('UnLink', false, null);
  }

  function iImage() {
    var imgSrc = prompt('Enter image location:', '');
    if(imgSrc != null){
    richTextField.document.execCommand('insertimage', false, imgSrc);
    }
  }

</script>

<body onLoad="iFrameOn();">
  <h2>Text Editor</h2>
  <form action="my_parse_file.php" name="myform" id="myform" method="post" onLoad="autosave_form();">
        <fieldset>
        <p>Entry Title: <input name="title" id="title" type="text" size="80" maxlength="80" /></p>
        <p>Entry Body:<br />

            <div id="wysiwyg_cp" style="padding: 8px; width: 700px;">

                <input type="button" onClick="iBold()" value="B" />
                <input type="button" onClick="iUnderline()" value="U" />
                <input type="button" onClick="iItalic()" value="I" />
                <input type="button" onClick="iFontSize()" value="Text Size" />
                <input type="button" onClick="iForeColor()" value="Text Color" />
                <input type="button" onClick="iHorizontalRule()" value="HR" />
                <input type="button" onClick="iUnorderedList()" value="UL" />
                <input type="button" onClick="iOrderedList()" value="OL" />
                <input type="button" onClick="iLink()" value="Link" />
                <input type="button" onClick="iUnLink()" value="UnLink" />
                <input type="button" onClick="iImage()" value="Image" />

            </div>

            <textarea style="display: none;" name="myTextArea" id="myTextArea" cols="100" rows="14"></textarea>
            <iframe name="richTextField" id="richTextField" style="border: #000000 1px solid; width: 700px; height: 300px"></iframe>


        </p><br />
        <input name="myBtn" type="button" value="Submit Data" onClick="javascript:submit_form();"/>
        </fieldset>
</form>
</body>

自动保护程序也可以 - 但只能使用textarea而不是iFrame。

// get the state of the form
function getFormState() {
  var fields = document.getElementsByTagName('form')[0].elements;
  if (fields.length == 0){return};
  for (var i = 1; i <= fields.length-1; i++) {
    var name = fields[i].getAttribute('name');
    if (name in localStorage && localStorage[name] !== null) {
        fields[i].value = localStorage[name];
    }
  }
}

// save the state of the form
function saveFormState() {
  var fields = document.getElementsByTagName('form')[0].elements;
  if (fields.length == 0){return};
  var populated = false;
  for (var i = 1; i <= fields.length-1; i++) {
    var name = fields[i].getAttribute('name');
    if (fields[i].value != '' && fields[i].getAttribute('type') != 'submit') {
       localStorage[name] = fields[i].value;
       populated = true;
    }
  }

  // display the time form data was saved (optional)
  if (populated) {
    var date = new Date();
    var hours = date.getHours();
    var mins = date.getMinutes();
    var secs = date.getSeconds();
    hours = (hours < 10) ? '0' + hours : hours;
    mins = (mins < 10) ? '0' + mins : mins;
    secs = (secs < 10) ? '0' + secs : secs;
    var msg = '[Form data was saved at ' + hours + ':' + mins + ':' + secs + ']';
    var timecont = document.getElementById('time_container');
    if (timecont !== null) {
        timecont.innerHTML = msg;
    }
    else {
        timecont = document.createElement('span');
        timecont.setAttribute('id', 'time_container');
        timecont.appendChild(document.createTextNode(msg));
        document.getElementsByTagName('fieldset')[0].appendChild(timecont);
    }
  }
}

// run the above functions when the web page is loaded
window.onload = function () {
  // check if HTML5 localStorage is supported by the browser
  if ('localStorage' in window && window['localStorage'] !== null) {
    // get the form state
    getFormState();
    // save the state of the form each 15 seconds (customizable)
    setInterval('saveFormState()', 15 * 1000);
  }
}

现在我需要一些绑定代码,它会将iFrame的innerHTML定期加载到textarea中。

function autosave_form() {
  var theForm = document.getElementbyID('myform');
  theForm.elements["myTextArea"].value = window.frames['richTextField'].document.body.innerHTML;
  setTimeout(yourFunction, 5000);
}

那我的家乡在哪里?或者我忽略了什么?请帮忙。 LIVEDEMO

2 个答案:

答案 0 :(得分:1)

<强>被修改!

似乎iframe是创建html编辑器的常用方法。

我确信解释here会对您有所帮助。

~~~

我不确定您是否可以访问iframe的innerHTML,因为它是跨站点脚本,出于安全原因这是禁止的。使用javascript访问iframe内容可能会导致访问被拒绝错误。

答案 1 :(得分:1)

您未正确使用iframe对象上的界面。要在同一个域中获取iframe的内容,您需要浏览contentWindow字段。例如:

function read_iframe() {
  return window.frames['richTextField'].contentWindow.document.body.innerHTML;
}

请记住,您无法在其他域上阅读iframe的内容。

您可以在https://developer.mozilla.org/en/docs/Web/API/HTMLIFrameElement

的HTMLIFrameElement方法和字段中找到完整的文档