4

I have a page where I open a new window like so

var myWindow = window.open("", "", "width=755.9100,height=347.7200");
myWindow.document.body.append(img);

I want to add styles some style to this new window from the previous window

@page {size: A4;margin: 0;@media print {html, body {width: 210mm;height: 297mm;}

How do I add this to head tag in html through js?

3 Answers 3

5

There is the window.matchMedia function in js:

The usage is quite simple:

if (window.matchMedia("(min-width: 400px)").matches) {
    /* the viewport is at least 400 pixels wide */
} else {
    /* the viewport is less than 400 pixels wide */
}

One more useful article is here.

Sign up to request clarification or add additional context in comments.

1 Comment

This only works for on load. The correct answer would have a rendered media query that would respond to window size changes on the fly.
3

style is also an HTML element, so you can append that in a similar manner as you are appending the img element

var myWindow = window.open("", "", "width=755.9100,height=347.7200");
myWindow.document.body.append(img);
var style = myWindow.document.createElement("style")
style.innerHTML = "@page {size: A4;margin: 0;@media print {html, body {width: 210mm;height: 297mm;}"
myWindow.document.head.append(style);

Comments

1

Note that checking MediaQueryList.matches does not actually add a media query to the CSS. You have to run this check every time the window changes. To do this, you should call addListener(callback) on the MediaQueryList in addition to checking the matches property directly.

For example, to apply your style to the <html> and <body> elements on printed pages:

let mediaQueryList = window.matchMedia("print");
function screenTest(e) {
    if (e.matches) {
        document.documentElement.style.width = "210mm";
        document.body.style.width = "210mm";
        document.documentElement.style.width = "297mm";
        document.body.style.width = "297mm";
    }
    else {
        document.documentElement.style.width = null;
        document.body.style.width = null;
    }
}
screenTest(mediaQueryList);
mediaQueryList.addListener(screenTest);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.