Tips for retrieving document body from a script embedded within document.write

I urgently need assistance! I am currently developing an application that retrieves a report from an API, and the JSON response includes HTML content. Unfortunately, due to the JSON format, I cannot directly open this in a new browser window.

Within my script, I am incorporating the following code snippet:

          let tmp = result.data;
          let spot = tmp.indexOf('</body>');
          let insert = `<div style="position:fixed; top:200px;left:20px; width:200px;font-size:15pt">
         

          <div class="camera">
            <video id="video" style='display:hidden'>Video stream not available.</video>
            <button  onClick='takepicture()'>Take photo</button> 
          </div>
          <canvas id="canvas" style='display:none;'></canvas>
        <!--<button onClick='genPDF()'>PDF</button>-->
          Press CTRL+S to save page as HTML
          <img id="testDownloadImage" src='' width=600 height=400 />
          </div>
          
          <script type='text/javascript'>
alert(document.body.innerHtml)
          // function clearphoto() {
          //     var context = canvas.getContext('2d');
          //     context.fillStyle = "#AAA";
          //     context.fillRect(0, 0, canvas.width, canvas.height);

          //     var data = canvas.toDataURL('image/png');
          //     // photo.setAttribute('src', data);
          //   }
            
            // Capture a photo by fetching the current contents of the video
            // and drawing it into a canvas, then converting that to a PNG
            // format data URL. By drawing it on an offscreen canvas and then
            // drawing that to the screen, we can change its size and/or apply
            // other changes before drawing it.

            async function takepicture() {
              let video = document.getElementById('video');
              let canvas = document.getElementById('canvas');

              let displayMediaOptions={video: true,displaySurface:'browser', logicalSurface:true, cursor:'never', audio: false};
              try{
                video.srcObject = await navigator.mediaDevices.getDisplayMedia(displayMediaOptions);
                // video.play();
                var context = canvas.getContext('2d');
                width=window.innerWidth;
                height=window.scrollHeight;
                if (width && height) {
                  canvas.width = width;
                  canvas.height = height;
                  context.drawImage(video, 0, 0, width, height);
                
                  var data = canvas.toDataURL('image/jpg'); //.replace(/^data:image\/(png|jpg);base64,/, "");
                  // photo.setAttribute('src', data);
                  document.getElementById('testDownloadImage').src=data;
                  // location.href=data;
                } else {
                  // clearphoto();
                }
              }
              catch(err) {
                console.log("An error occurred: " + err);
              }
              finally{
              let tracks = video.srcObject.getTracks();
              tracks.forEach(track => track.stop());
              video.srcObject = null;
              }
            }
        </script>
          `
          let newStr = [tmp.slice(0, spot), insert, tmp.slice(spot)].join('');
          document.write(newStr);

This implementation is essential for adding a print screen feature to capture images of the report. Despite trying various tools to convert the HTML to PDF or saving the entire page, these methods have proven ineffective due to the extensive XSLT and scripting used in displaying the results, leaving me with no choice but to resort to using the print screen option.

While WebRTC effectively addresses this issue, there is one minor challenge: The use of document.write hinders me from accessing the document.body, even though the provided code represents a properly structured page.

How can I leverage the embedded script to render and capture the page as an image successfully?

Your help is greatly appreciated!

Answer №1

I encountered a similar issue, but found a creative solution by implementing an iFrame and moving the script outside of it. By adjusting the height of the iFrame to match the scrollHeight of its document, I was able to create the illusion that the content spanned the entire page. This allowed me to achieve my goal of capturing the entire page while keeping the script separate from the main content.

Appreciate any feedback or suggestions on this approach. It seems to have resolved the issue for now.

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

Following the submission of a POST request, an error occurred stating: "Unable to assign headers once they have been sent to

I'm having trouble figuring out what's wrong with my code. Whenever I send a post request, I get an error message saying "Cannot set headers after they are sent to the client". My model includes a comment schema with fields for user, content, and ...

When utilizing jQuery and Ajax for form submission, PHP is unable to retrieve any data

I'm encountering an issue when trying to submit a form with only a radiobutton group named radiob. The script I am using for submitting the data is as follows: <script type="text/javascript"> $(function() { $("#myForm").submit(funct ...

utilizing array.map() to nest multiple layers of arrays

I am facing a challenge with a JavaScript array structure that contains three top-level objects. Each of these objects has an "teamLineup" array, which in turn holds two more objects named "team". These "team" objects have another array called "starters", ...

Using axios with async/await to handle unresolved promises in Javascript

I'm facing a challenge with a piece of code I've been working on. Despite my efforts to find a solution online, I haven't had any success so far. Here is the code snippet in question: const fetchSidebarData = async () => { let da ...

The Firebase JQuery .on method is incrementally updating individual values in an array instead of updating them all simultaneously

I am trying to update the values of the orders placed by users on the Corporate's page without a refresh. I have implemented the jQuery .on method for this purpose. However, the values are being returned one by one from the array created for the order ...

Encountering an error with Next.JS when using the "use client" directive

Recently encountered a bizarre issue with my next.js project. Every time I input "use client"; on a page, it triggers a "SyntaxError: Unexpected token u in JSON at position 0". Here's the code snippet for reference: "use client" ...

Finding the Ideal Location for Controllers in an Express.js Project

I'm relatively new to software development and one concept that I find challenging is organizing the directory structure of various projects. As I prepare to embark on an Express project, I prefer keeping controller classes separate from route callbac ...

Implementing dynamic AngularJS functionality within an older HTML structure using JQuery

I am facing an issue while trying to load dynamic content using AngularJS. In my system, I have legacy pages that utilize JQuery for dynamic loading. However, as I am developing new features with AngularJS, I am encountering the same problem with dynamic ...

When there is an expensive calculation following a Vue virtual DOM update, the update may not be

Currently, I am facing an issue with adding a loading screen to my app during some heavy data hashing and deciphering processes that take around 2-3 seconds to complete. Interestingly, when I removed the resource-intensive parts, the screen loads immediate ...

Challenges surrounding jQuery's .before

Currently, I am in the process of creating a simple carousel consisting of 4 divs. The carousel is utilizing 2 jQuery functions to position a div at either the first or last slot. The transitions being used are only alpha transitions as there is no need fo ...

How to set cells to plain text in google sheets

I've been grappling with a formatting issue that I'm hoping someone can assist me with. In my script, there's a point where I need to combine the date value (e.g., 11/20/2020) from one column with the time (3:00 PM) from another column. This ...

Tips for preventing the appearance of two horizontal scroll bars on Firefox

Greetings, I am having an issue with double horizontal scroll bars appearing in Firefox but not in Internet Explorer. When the content exceeds a certain limit, these scroll bars show up. Can someone please advise me on how to resolve this problem? Is ther ...

Handling an Express server that receives a request with no data

I'm struggling with a problem where I am unable to retrieve a basic JSON object. When I log it to the console, all I see is {}. Let me showcase the server code below: const express = require("express"); const app = express(); app.listen(3000); app.us ...

Improving the efficiency of my conditions in a function with Vue JS

Does anyone have any suggestions on how to optimize this function? I feel like it could be shortened to improve its efficiency. Any help or advice would be much appreciated. Function: onStudentActionSelect: function () { if (this.selectedRows.length ...

What is the best way to transfer a content script variable to a background script in a Chrome Extension?

I am looking to transfer a variable named "website_hostname" from the content script to the background script. This variable holds the hostname of the website you are currently visiting. Content Script: var website_hostname = window.location.href; //Cod ...

Encountering difficulties when attempting to load a module with the "js" extension in a TypeScript environment

When making a GET request with Systemjs, the extension .js is not being added to the URL. These are my TypeScript Classes customer.ts import {Address} from "./Address"; export class Customer { private _customerName: string = ""; public Customer ...

Execute HTML and JS files through Eclipse PDT to view in a web browser

Is it possible to open HTML and JS files in a web browser within Eclipse PDT? Right now, only PHP files seem to launch successfully, otherwise an "Unable to Launch" dialog pops up. Any advice is appreciated! ...

How to implement various middlewares in Express.js depending on the current environment using NODE_ENV?

My dilemma involves utilizing two different middlewares based on NODE_ENV: router1 for production and router2 for testing and development environments. I'm currently using the following code snippet: if( process.env.NODE_ENV === 'prod' ) { ...

Issues encountered when trying to use default color classes in Tailwind CSS

I'm currently working on a React project that utilizes the Tailwind CSS Framework. To integrate Tailwind into my React app, I used NPM to install it in the following way: npm install -D tailwindcss postcss autoprefixer npx tailwindcss init -p After i ...

Using Javascript to group elements by JSON data

I have an array of JSON objects and I'm attempting to organize it by a specific element. I came across some code example on grouping JSON format from this link const groupBy = prop => data => { return data.reduce((dict, item) => { ...