Insert information into the window before it loads

Exploring the process of opening new windows using JavaScript.

var myWindow = window.open();
myWindow.document.write('html');            

Is it feasible to inject content into the document before the window fully loads? I aim to include a complete HTML structure, along with some JavaScript code. Despite attempting to concatenate the HTML code, it failed to work even when using my trusty code editor.

Answer №1

To prepare the entire document in advance of opening it, one option is through a data URI or an Object URL that points to a Blob.

// Utilizing Blob method which is more modern with minimal restrictions
function createWindow(code) {
    var blob = new Blob([code], {type: 'text/html'}),
        url = URL.createObjectURL(blob),
        win = window.open(url, '_blank');
    URL.revokeObjectURL(url); // cleanup
    return win;
}
createWindow('\
<!doctype html>\n\
<html>\n\
    <head>\n\
        <title>Hello World!</title>\n\
    </head>\n\
    <body>\n\
        <span>Foobar</span>\n\
    </body>\n\
</html>\n\
');

Alternatively, you can also use this approach:

// Employing data URI method, which has more limitations but is compatible with older browsers
function createWindow2(code) {
    return window.open('data:text/html,' + window.encodeURIComponent(code), '_blank');
}
createWindow2('\
<!doctype html>\n\
<html>\n\
    <head>\n\
        <title>Hello World!</title>\n\
    </head>\n\
    <body>\n\
        <span>Fizzbuzz</span>\n\
    </body>\n\
</html>\n\
');

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

Communication through Collaboration Diagrams

For my software engineering project, I am working on creating communication diagrams. However, I am struggling with understanding how to draw if-then statements. Can anyone provide assistance with this? I have tried looking on YouTube for tutorials, but u ...

What is the process of using AJAX, JavaScript, and HTML to submit data to a remote

I need help with sending data from an HTML page to a server. I have a JSON example below that illustrates what I want to achieve. On my HTML page, I have a question label and four options (A, B, C, D) as radio buttons. After clicking the send button, I ...

JavaScript regular expressions: filtering out results from the output

I'm trying to extract a specific number from a dynamically added string. The text looks like this: nisi non text600 elit, where 600 is the number I need to retrieve. Is there a way to achieve this without replacing the word text? var str = ('nis ...

Spotlight the content of the file obtained from GitHub

I'm having trouble with syntax highlighting for code fetched from GitHub. fetch("https://raw.githubusercontent.com/Ayanmullick/test/master/AutomationAcc/test1.ps1") .then(response => response.text()) .then(data => document.getElem ...

The absence of req.body in the app reflects an undefined state

I'm encountering an issue with my app and I believe showing you my code is the best way to explain the problem: var Meetup = require('./models/meetup'); module.exports.create = function (req, res) { var meetup = new Meetup(req.body); c ...

Check if the element is not present in the array, then add it to the array

I am attempting to generate an array in JavaScript with unique elements extracted from a JSON feed. My thought process is possibly too influenced by PHP, where a simple script like the one below would suffice: $uniqueArray = array(); foreach($array as $ke ...

Utilizing jQuery to enable a div to follow the touchmove or mousemove events while also automatically

I am looking to create a basic function in my jQuery script. I want the pages to slide horizontally in response to the movement of a finger or cursor on the screen. While there are many plugins available for this purpose, I prefer a simple, customized solu ...

Using JWPlayer 6 and JWPlayer 7 simultaneously in one project - how is it done?

Trying to incorporate both JWPlayer 6 and JWPlayer 7 into my expressJS, AngularJS project has been a challenge. While they each work independently without issue, bringing them together has proven to be tricky. In my index.html file, I include them separat ...

Steps for creating a dynamic validation using a new form control

I have an item that needs to generate a form const textBox = { fontColor: 'blue', fontSize: '18', placeholder: 'email', name: 'input email', label: 'john', validation: { required: false } ...

What is the best way to enable visitors to share the current page on blogger, similar to the functionality of Facebook's

I'm looking to integrate a button on my website similar to Facebook's like button that allows users to share my site on Blogger. However, after checking Blogger's developer site, it appears that there is no equivalent JavaScript code availab ...

Maintain the values of radio buttons, dropdowns, and checkboxes using Javascript

When I click on a radio button, it activates a drop down menu. Upon selecting different values from the drop down, various checkboxes become visible. Now, I want to preserve the selection of the radio button along with the selected drop down values and ch ...

Creating a mapping in Node.js to write to a serial port and then retrieve the

Currently, I am utilizing the node-serialport module for serial port communication. My goal is to send the command ATEC and receive a response of ECHO. However, the process of sending and receiving data is asynchronous (after sending the data, the timing ...

Express 4.13.4 appears to be disregarding the cookie's expiration date when the moment.toDate() function is used

I've been encountering an issue where I am attempting to set a cookie with a specific expiry date of 3 months, but the expiration is not setting correctly. Using momentJS, I created a date object for the desired time. The console confirms that the co ...

The issue with Jquery .html() function causing spaces to disappear between words

When utilizing jQuery's .html() property to populate a select box, I encountered an issue where the spaces between words were being trimmed down to just one space. Despite including multiple spaces in the option, it would always resolve to a single sp ...

Using AJAX to upload an image and passing multiple parameters

I'm facing an issue when trying to upload an image along with other input text in a form and send it to ajax_php_file.php. Whenever I upload the image, all my input text fields appear empty. Any assistance would be greatly appreciated. Thank you very ...

Converting date formats in HTML with the help of JavaScript

I am completely new to JavaScript and would greatly appreciate any assistance. Within my HTML code, I have dates extracted from a form that need to be displayed. <body> Test Date<br> <span id="test">{{TestDate|"dd/MM/yy"}}</span> ...

Retrieve an array of specific column values from an array of objects using Typescript

How can I extract an array from an array of objects? Data var result1 = [ {id:1, name:'Sandra', type:'user', username:'sandra'}, {id:2, name:'John', type:'admin', username:'johnny2'}, ...

Developing original data from an array in JavaScript

I am looking to create an API body for use in JavaScript fetch. The array contains around twenty items and I need to iterate through it using a loop. Here is an example of my array of objects: [ { name:"x",lname:"y" }, { name:" ...

Make a quick call to the next function within the error handling module for a

Currently, I am facing an issue while trying to call the next function within the error handler of my node + express js application. In each controller, I have a middleware known as render which is invoked by calling next, and I wish to achieve the same f ...

Troubleshooting: jQuery AJAX .done() function failing to execute

Currently, I have a piece of code that is being utilized to dynamically load HTML into a CodeIgniter view: $.ajax({ type:"POST", url: "Ajax/getHtml", data: { u : conten ...