简体   繁体   English

如何在DOMParser生成的文档中使用getComputedStyle(没有defaultView或window对象)?

[英]How to use getComputedStyle with DOMParser produced document (no defaultView or window objects)?

I have this code (simplified): 我有此代码(简体):

var s = '<div>html...</div>';  
var parser = new DOMParser();  
var doc = parser.parseFromString(s, 'text/html');  

The resulting document object does not have a defaultView nor a window properties, so is there a way to call getComputedStyle() ? 结果文档对象没有defaultView或window属性,因此有没有一种方法可以调用getComputedStyle()?

To explain more: I use code like this in a Firefox extension that performs batch DOM manipulation on HTML files and serializes then writes the modified documents back to disk. 进一步说明:我在Firefox扩展中使用了类似的代码,该扩展对HTML文件执行批处理DOM操作并进行序列化,然后将修改后的文档写回到磁盘。

As pointed out by Mike, there is a hiddenDOMWindow, so I adapted his code to something like this: 正如Mike所指出的,有一个hiddenDOMWindow,所以我将他的代码修改为如下形式:

const { Services } = Cu.import("resource://gre/modules/Services.jsm");
var s = '<div style="color:red;font-family:Tahoma">html...</div>';  
var parser = new DOMParser();  
var doc = parser.parseFromString(s, 'text/html');  
var div = doc.querySelector("div");
var win = Services.appShell.hiddenDOMWindow;

var div2 = win.document.importNode(div, true);
var style = win.getComputedStyle(div2);
alert( style.getPropertyValue('color') ); //alerts rgb(255, 0, 0) which is correct!

Thanks Mike, I never knew there was a hiddenDOMWindow. 谢谢Mike,我不知道有一个隐藏的DOMWindow。

This should work from either content or an extension: 这应该从内容或扩展名起作用:

var s = '<div>html...</div>';  
var parser = new DOMParser();  
var doc = parser.parseFromString(s, 'text/html');  
var div = doc.querySelector("div");

var style = window.getComputedStyle(div);

If you don't have access to a window eg from an extension then you could do it this way: 如果您无权访问某个窗口(例如,从扩展名访问),则可以通过以下方式进行操作:

const { Services } = Cu.import("resource://gre/modules/Services.jsm");

var s = '<div>html...</div>';  
var parser = new DOMParser();  
var doc = parser.parseFromString(s, 'text/html');  
var div = doc.querySelector("div");
var win = Services.appShell.hiddenDOMWindow;

var style = win.getComputedStyle(div);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM