0

如您所知,网页是 html 文件、一个或多个 css 文件和一个或多个 javascript 文件的联合:前两个元素由浏览器解析以生成 DOM 和其他对渲染有用的数据结构页 。

Javascript 文件是由引擎执行的,它们可以改变 DOM 的值或与 css 相关的数据结构的值,因此,在执行 javascript 之后,网页的“实际状态”可以不同于由原始 html 和 css 代码静态描述。

我需要开发一个 firefox 插件,它可以获取网页的“实际状态”并将其作为一对 html + css 文件存储到磁盘。

因为 html 文件很简单,我需要序列化 ​​DOM。我担心的是 css:我可以遍历 DOM 并为每个元素获取其样式表,但它会非常慢并且会生成未优化的 css 代码。

让我们举个例子

我有这个 html 代码:

<html>
    <head>
         <title>Test</title>
         <link type="text/css" rel="stylesheet" href="style.css"  />
         <script type='text/javascript' src="changebackground.js" > </script>
    </head> 
    <body>
         <div  class="divclass" > 
            <form> 
                <h2>click to change the background</h2>
                <input type="button" value="version" onclick="changebg()" />
            </form>
         </div>
    </body>

Style.css 有这样的定义:

.divclass{
          margin: .5in; 
          height: 400px;
}

body{
      background-color: white;
      color: blueviolet;
}

和 changebackground 有这个代码:

function changebg() {
     document.body.style.backgroundColor = 'black';
 }

显然,单击按钮后,背景颜色变为黑色。我的目标是编写一个附加组件,在此更改之后,将样式修改后的 css 还给我,即:

.divclass{
          margin: .5in; 
          height: 400px;
}

body{
      background-color: black;
      color: blueviolet;
}

有任何想法吗?

4

1 回答 1

1

You don't actually need to traverse anything. Inline styles are already part of the, so you get that for free, e.g.:

elem.style.width = "100px";
elem.outerHTML == '<elem style="width: 100px;>";

So to produce a "dump" of the current DOM, incl. inline styles, etc. do:

var html = document.documentElement.outerHTML;

You may also want to serialize document.doctype.

In the unlikely event that a script actually messes with external stylesheets (<link rel="stylesheet">, you may do something like what I described in "Get text of a modified stylesheet" to get the current set of rules. Again, inline styles (<style> and style= attributes) are already present in .outerHTML.

EDIT: What you ask now is not possible, because this is not how inline styles work. Consider the following html fragment:

<div>first div</div>
<div>second div</div>

Now the following code runs:

document.querySelector("div").style.background = "black";

This will cause the first div to have an inline style:

<div style="background: none repeat scroll 0% 0% black;">first div</div>
<div>second div</div>

Demo Fiddle

How would that rule look like? div { background: black; } is obviously wrong, as this would affect all divs.

You could generate new classes and/or ids, but then you need to manipulate and store the DOM, and could have used my original answer in the first place.

于 2013-09-27T16:08:11.447 回答