What is causing the overwhelming reaction when using window.open() to open the same file?

I'm having trouble when trying to print a web page using JavaScript. The window.open() function does not load the style sheets of the same file.

Here is my JavaScript code:

function Print() {
    printWindow = window.open("", "mywindow", "location=1,status=1,scrollbars=1,width=600,height=600");
    printWindow.document.write("<div style='width:100%;'>");
    printWindow.document.write("<input type='button' id='btnPrint' value='Print' style='width:100px' onclick='window.print()' />");
    printWindow.document.write("<input type='button' id='btnCancel' value='Cancel' style='width:100px' onclick='window.close()' />");
    printWindow.document.write("<select id='cboprintSize' onchange='document.getElementById(\"divContainer\").style.width = document.getElementById(\"cboprintSize\").value + \"px\";'><option value=\"300\">A4</option><option value=\"500\">A5</option></select>");
    printWindow.document.write("<div id='divContainer' style='width:500; height:700; background-color:white'>");
    printWindow.document.write("<table width='100%'><tr><td>");
    printWindow.document.write(document.getElementById('printForm').innerHTML);
    printWindow.document.write("</td></tr><table>");
    printWindow.document.write("</div>");
    printWindow.document.write("</div>");
    printWindow.document.close();
    printWindow.focus();
}

And here is the ASP.NET form code:

<input type="button" id="btnCall" onclick="Print()" value="Print" />

<form runat="server" id="printForm">
<table width="100%" border="0" cellspacing="0" cellpadding="0">
    <tr>
        <td colspan="3">
            <table width="100%" border="0" cellspacing="0" cellpadding="0">
                <tr>
                    <td>
                    <img src="images/incident1.png" alt="First Line Incident" title="First Line Incident" align="absmiddle" class="cardIcon"  border="0">
                    </td><td width="100%"><span class="title">&nbsp;PRI1307-006</span></td>
                    <td align="right" nowrap>
                    <a href="#" id="public_edit">
                    <span class="value">
                    <img src="images/edit.png" class="iconNavBar" style="border: 0px;" title="Edit" width="24" height="24"></span>
                    </a>
                    <a href="#" dynamicMenu="print"  target="_blank">
                        <span class="value">
                        <img src="images/icon_printable_version.png" class="iconNavBar" style="border: 0px;" title="Printable version" width="24" height="24">
                        </span></a></td>
                </tr>
            </table>
</form>

Answer №1

When you are creating a new document in a separate window, it's important to note that the stylesheets from the parent page will not automatically load in this new window.

To ensure your styling is applied properly, you can include all necessary HTML and link your external stylesheets directly within the new document:

newWindow.document.write("<html><head>");
newWindow.document.write("<link href='style.css' type='text/css' rel='stylesheet' />");
newWindow.document.write("</head><body>");
...
newWindow.document.write("<div style='width:100%;'>");
...
newWindow.document.write("</body></html>");
newWindow.document.close();

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Executing PHP script within a Node.js socket server program

I have a JavaScript file running a normal TCP socket using node.js. Before sending a response back to the client, I need to validate the data using some PHP (MySQL) code. Can someone guide me on executing this PHP code inside the JavaScript file? Most of t ...

Is it possible to set up client certificate configurations within the web.config file?

Currently I am managing an SSL application and am looking for a way to manage which folders either ignore, require, or accept client certifications. The main objective is to have a particular sub-folder within the webApp that ignores client certification. ...

Converting strings into time formats in MongoDB

My string appears as follows: schedule_time = { start_time : "13:00", end_time : "14:10" } Now I need to convert it into time in MongoDB. I attempted using dateFromString but encountered some issues. The aggregation query: db.getCollection('appoi ...

Move the internal array pointer forward to the next record in order to apply the insertAfter function within the jquery code

As a new jQuery user, I'm attempting to develop a jQuery function using data provided by PHP. My goal is to arrange DIV elements in order of their values using insertAfter method. However, I seem to be encountering some difficulty in advancing the poi ...

Display information from a different model using ASP.NET Entity Framework

Two tables: TestAnswer and question This Create Script is generated by Entity Framework with added viewbags Instead of a select list, I want to display values from the Question table as normal text in my TestAnswer view (@Html.DisplayFor(model => mode ...

Querying MongoDB in Loopback is posing a challenge

My attempt to query MongoDB from a LoopBack model is not yielding any results. This is an example of how my document appears in MongoDB: {"_id":"5b9f8bc51fbd7f248cabe742", "agentType":"Online-Shopping", "projectId":"modroid-server", "labels":["category", ...

What could be the reason for one function returning undefined from identical API calls while the other functions produce successful results?

As I delved into incorporating the TMDB API into my project, a perplexing issue arose that has left me stumped. Despite utilizing identical code snippets in two separate files and functions, one of them returns undefined while the other functions flawlessl ...

Can you explain the process of retrieving API information from a component directory with Next.js?

In the components folder, I have created a reusable component that displays user details for those who log into the system in the header section. Currently, I am attempting to utilize getInitialProps with isomorphic-unfetch. static async getInitialProps( ...

Integrate a PHP variable into an HTML/JavaScript statement that was previously transformed from PHP

Incorporated within this PHP variable is a mix of HTML and JavaScript code. My task is to enhance it by adding another PHP variable. Specifically, I have a PHP variable denoted as $user->user_email. How can I seamlessly integrate this variable into th ...

ES6 Generators: lack of informative stack trace when using iterator.throw(err)

The ES6 approach: iterator.throw(err) is often explained as inserting an exception as if it happened at the yield statement within the generator. The challenge lies in the fact that the stack trace of this exception does not include any information about t ...

Mapping over an array and ignoring any undefined properties in a dynamic object

Looking for a way to dynamically create objects in the 'map' function to reduce the final array size. The goal is to avoid adding properties with undefined values. For example, if 'offst: undefined', skip this property but add others wi ...

Building a React.js application and fetching information with Ajax

In my quest to create a high-speed React.js application that functions as a game, I find myself in need of displaying real-time data. However, the traditional method of loading this data from the server using Ajax doesn't quite align with the reactive ...

Ionic: How come my image is not loading with HTTP.GET?

I have been attempting to populate a gallery in my Ionic application by fetching images from a JSON file, but I am encountering issues. While following a guide on creating a grid-like image gallery using the Ionic framework (https://blog.nraboy.com/2015/03 ...

Convert web address object to URL string

Currently, I am dealing with a stringified object stored in my localStorage, const stringifiedURLObject = fromLocalStorage I have attempted to parse this string using JSON.parse to obtain a normal Url Object. Now, I am looking to convert this object int ...

What is the best way to ensure that my $.ajax POST call works seamlessly with SSL?

Below is the JavaScript code I am using: parameter = "name=" + name + "&email=" + email + "&phone=" + phone + "&comments=" + comments; $.ajax({ url: 'sendEmail.php?' + parameter, success: ...

Incorporate a div beside a button using componentDidMount in a React component

Upon page load, I aim to position an info icon div next to a button node. However, the button node is not available when componentDidMount is triggered. I have attempted to use setTimeout, but its effectiveness varies depending on the amount of data in th ...

Tips for setting multiple selected values in a listbox

I am having trouble setting selected values for a multi-select listbox. Whenever I try to set values, only the last value (Paris) gets selected. However, I need to be able to select multiple values in the listbox. Here is my code: <select size="4" na ...

Is there a way to remove createdAt and updatedAt from every query in Sequelize?

Currently, I am utilizing Node 14 and Sequelize to model an existing Postgres database. The tables that have already been created do not contain the createdAt or updatedAt columns, so my intention is to set up Sequelize in a way that it will never attempt ...

Conditionally Add Columns to jQuery Datatables

I am working with a jQuery datatable to showcase data retrieved through an AJAX request. However, I am interested in adding a third column to the table specifically for administrators, allowing them to delete entries. Can someone guide me on how to incorpo ...

Bring in a particular module from the natural library (webpack)

I have been utilizing the npm natural library for tokenization, specifically in one line of code: let token = natural.StemmerJa.prototype.tokenizeAndStem(searchWord, true); My concern lies in how to properly import it in webpack, given that tokenizeAndSte ...