Javascript listen for style changes made in developer-tools

混江龙づ霸主 提交于 2019-12-06 01:14:55

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