Is there a way to detect style changes made only in the developer-tools (inspect element)?
I want to allow to save them if the user is logged in as admin.
You can access the styles of a HTMLElement using element.style
in JavaScript. So you could probably save the styles on page load, check them again when the user initiates a save and compare -- the difference would be the users changes.
As for detecting them as soon as they happen, you can use MutationObserver
to get notified of attribute changes on the page. This works for when you add styles to a specific element in the Devtools, but not for editing existing styles and (I think) adding styles to existing selectors. I'm not sure if there is a way to get an event when these change.
Edit: actually, it seems as if checking element.style
has the same limits as using MutationObserver
: only styles added for the specific element (that is, styles that show up as inline styles in the DOM) show up. There might be a way to actually access all styles, but I'm not aware of it.
You could use the MutationObserver
to be notified when the DOM elements are modified. See the snippet below to see it working.
Note that it does not tell you whether the mutation was triggered by Javascript on your page, or through the developer tools. So, you have the added burden of tracking when your JS changes something and when the user changes something.
var target = document.getElementById('targetDiv');
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
console.log("New Mutation:");
mutation.addedNodes.forEach(function(node) {
console.log("Added: " + node.nodeName);
});
mutation.removedNodes.forEach(function(node) {
console.log("Removed: " + node.nodeName);
});
});
});
var config = {
attributes: true,
childList: true,
characterData: true
};
observer.observe(target, config);
function mutate() {
target.innerHTML += Math.random() + "<br/>"
}
#targetDiv {
margin: 10px;
width: 500px;
padding: 5px;
}
<div id="targetDiv"></div>
<button id="mutate" onclick="mutate()">Mutate the Div</button>
来源:https://stackoverflow.com/questions/46322012/javascript-listen-for-style-changes-made-in-developer-tools