[英]How to store text content of a browser textarea on a local disk
我需要將已編輯的“ textarea”文本(> 1 MB)臨時存儲在本地磁盤上以脫機工作。 稍后,我想再次加載它並繼續進行編輯,就像使用普通桌面應用程序一樣。
我知道我可以輕松加載文本文件並將其添加到textarea。 但是如何保存呢? 關於此問題,我在博客上投入了大量精力,並且有一些嚴肅的解決方法建議,例如IndexdDB和Web SQL Storage。 但是,哪一種可以在所有主流瀏覽器上使用,並且在不久的將來會得到支持? 我目前沒有找到任何明確的陳述。
您正在尋找主機的( window
) Storage
對象,特別是localStorage
變體 (因為sessionStorage
變體僅保留-您可能在會話期間猜到了它)。
所有現代瀏覽器均支持該文件(按規范),通常將保留5 MB。
您可以在w3schools編輯器中嘗試以下示例(由於安全原因,由於它不能在堆棧片段,jsfiddle,realtime-html-editor等上運行)。
還要注意,它不能在本地保存的網頁中使用,因為當前瀏覽器仍需要完全限定的域名才能將安全措施和鏈接存儲(還包括cookie等)應用到正確的域!
這就是為什么我提到可怕的w3schools(因為如果沒有webhosting和運行,我找不到可以工作的地方)。
最后,上面的“證明”還旨在解釋為什么您可能在本地嘗試過的示例不起作用。
最后的解決方法是設置本地網絡服務器,並將瀏覽器指向(本地)IP地址,從而解決瀏覽器需要有效域才能將存儲鏈接到的“問題”!
(我非常喜歡使用需要有效URL的此類代碼來進行快速且可移植的本地修改,這非常微小 。)
這是上面提到的(經過測試的)代碼,可以幫助您入門:( 評論應對此進行解釋)
<form>
<textarea id="save_my_txt" placeholder="Enter text here.."></textarea>
<input type="reset" value="reset">
</form>
<script>
(function(elm, key){
// check for local storage support
if(window.localStorage){
// if there was data stored, retrieve it and output it to the elment
if(localStorage.getItem(key)) elm.value=localStorage.getItem(key);
// when the element is blurred and the content is changed
elm.onchange=function(){
// check if the textarea is empty and save or remove localStorage entry
localStorage[this.value?'setItem':'removeItem'](key, this.value);
};
// finally, a form's reset does NOT fire it's element's onchange()
// either 'fix' the reset-button (using `this.form.reset()`)
// or the form's `onreset` handler (example below:)
elm.form.onreset=function(){ localStorage.removeItem(key); };
} // else handle the lack of Storage-support differently..
}( document.getElementById('save_my_txt') // pass in a textarea
, 'my_txt_str' // pass key-identifier for localStorage
)
); //end IIFE
</script>
請注意,由於您已經請求了現代/未來瀏覽器的支持,因此我使用了html5 placeholder
(減輕了一些為正確操作defaultValue
進行重置所需的JavaScript)。
希望這可以幫助!!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.