Search code examples
javascriptfirefoxgecko

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.


Solution

  • 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 e.g. 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);