简体   繁体   中英

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() ?

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.

As pointed out by Mike, there is a hiddenDOMWindow, so I adapted his code to something like this:

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.

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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