I have some Javascript that is opening a blank window, assigning it with a stylesheet and then writing some text to it. This is all working fine except that the content is not having the styles applied to it.
The code looks like this:
var newWindow = window.open('', 'SecondWindow', 'toolbar=0,stat=0'); var style = newWindow.document.createElement('link'); style.type = 'text/css'; style.rel = 'stylesheet'; style.href = 'styles/style.css'; newWindow.document.getElementsByTagName('head')[0].appendChild(style); newWindow.document.body.innerHTML='<p class='verystylish'>Hello world!</p>';
If I use the Firefox Web Developer tools to view the generated source, save that as an html file and then open the html file manually, it applies the styles correctly, so it looks as though I need to be doing something to force the browser to apply the styles or re-render the page somehow. Any suggestions?
Edited to add, the generated source looks like this:
<html> <head> <title></title> <link href='styles/style.css' rel='stylesheet' type='text/css'> <head> <body> <p class='verystylish'>Hello world!</p> </body> </html>
The problem being that no style whatsoever is assigned to the paragraph. But opening a file with the same source code renders correctly.
A new window opens by default with the URL ‘about:blank’. Relative URL references won’t work for this reason. To change the location of the window to match the original document, call:
You should then write the skeleton of the document you want to the window. You can include the stylesheet now if you want, as document.write is a more reliable way of adding a stylesheet across older browsers than DOM methods. This method also allows you to write a DOCTYPE so you don’t unexpectedly end up in Quirks Mode.