Save changes made by content editable on any website

大兔子大兔子 提交于 2020-08-24 07:57:10

问题


The following code allows any website to be completely editable temporarily:

document.body.contentEditable = "true";

If I want to save the settings made to a particular website using this method, how can I achieve this using Javascript and if needed PHP, so that next time I visit this URL, the website updates automatically with the settings made. Is this even possible? Is there an extension already available?


回答1:


Here's a way you can do this using vanilla JS.

Here's JSFiddle since StackOverflow doesn't allow localStorage to be executed on the website as a security feature.

How it works:

  1. Using window.onload = function() {...}, check if 'content' key exists in localStorage
  2. If it does, load the data into <div class="content">
  3. Upon pressing Edit button, contentEditable is toggled
  4. Here you can use any method to save the data. I used content.contentEditable === 'false' to save the innerHTML data to 'content' key.

To Note: localStorage is saved in your browser locally, use databases or anything similar to display edits to all viewers.


// Load content onload if it exists in localStorage
window.onload = function() {
	if(localStorage.getItem('content')) {
		document.querySelector('.content').innerHTML = localStorage.getItem('content');
  }
}

let editBtn = document.querySelector('#edit_content');
let content = document.querySelector('.content');

editBtn.addEventListener('click', () => {
  // Toggle contentEditable on button click
	content.contentEditable = !content.isContentEditable;
  
  // If disabled, save text
  if(content.contentEditable === 'false') {
  	localStorage.setItem('content', content.innerHTML);
  }
});
.content {
  border: 1px solid;
  padding: 15px;
}
<div class="content">
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
</div>
<br>
<button id="edit_content">Edit</button>



回答2:


[Answer basically salvaged from the comments, if it was here would be easier for people to read]

Save the data inside the <div> (not the entire page) into a localStorage. You can save when the document.body.contentEditable is disabled. You can then re-load it into the html when the page reloads.



来源:https://stackoverflow.com/questions/50876234/save-changes-made-by-content-editable-on-any-website

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!