collecting JavaScript objects directed to console.log

I attempted capturing the JavaScript console log using the method mentioned here on Stack Overflow. However, I am facing difficulty in retrieving the object along with a text message. Below is the code snippet that I have been working with:

var obj={result:true,type:"text"};

(function(){
    var oldLog = console.log;
    console.log = function (message) {
        alert(message);  // The object does not get returned
        oldLog.apply(console, arguments);

    };
})();

console.log("hi",obj);

What should I replace message within the alert line of code to successfully receive the obj object as well?

Answer №1

You have a custom console.log function where you are passing multiple arguments but only alerting the first argument. To rectify this, iterate through all the arguments passed to your custom console.log function and alert each one:

var obj={result:true,type:"text"};

(function(){
    var oldLog = console.log;
    console.log = function () {
        for (var i = 0; i < arguments.length; i++) {
            alert(arguments[i]);
        }
        oldLog.apply(console, arguments);

    };
})();

console.log("hi",obj);

If you prefer to display all objects in a single alert, you can concatenate their string representations within the for loop and call alert once at the end:

var obj={result:true,type:"text"};

(function(){
    var oldLog = console.log;
    console.log = function () {
      var result = "";  
        for (var i = 0; i < arguments.length; i++) {
            result += arguments[i] + " ";
        }
        alert(result);
        oldLog.apply(console, arguments);

    };
})();

console.log("hi",obj);

Lastly, if you want to view the object contents in your alert, consider using JSON.stringify() on each argument before processing.

Answer №2

Give this a shot

let data={outcome:true,category:"string"};

(function(){
    let oldPrint = console.log;
    console.log = function () {

            alert(JSON.stringify(arguments));

        oldPrint.apply(console, arguments);

    };
})();

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

Retrieve the URL of a particular XML document from the server using a PHP script, then dynamically load it into a JavaScript file for further processing

As I work on my website, users have the ability to upload and download files while I generate an XML log with operation details. One page on the site displays a table created by reading this XML log. Everything functioned properly when it was all stored l ...

"Exploring the process of assigning input data to a different variable within a Vue component

Reviewing the code snippet I currently have: <template> <div> <input v-model.number="money"> <p>{{ money }}</p> </div> </template> <script> name: 'MyComponent', data () { ...

Incorporating an external library into a Node.js virtual machine

I'm currently working on a nodejs library that enables users to write and execute their own JS code. Here is an example: var MyJournal = Yurnell.newJournal(); module.exports = function(deployer) { MyJournal.description = "my first description& ...

What are the steps to implement an audio stream in a JavaScript React application?

I have been working on integrating a web dialer system into my JavaScript NextUI React app. After making some progress, I can successfully dial and hear my voice through the phone. However, I am encountering an issue where I cannot hear the other person sp ...

Implement a delay for a specific function and try again if the delay expires

In my TypeScript code, I am utilizing two fetch calls - one to retrieve an access token and the other to make the actual API call. I am looking to implement a 1-second timeout for the second API call. In the event of a timeout, a retry should be attempted ...

Updating CSS stylesheets dynamically when onchange event occurs

I am currently able to dynamically change style rules using JS, but I feel that this is limiting. I would prefer to be able to swap entire CSS stylesheet files easily. Do you have any suggestions on how to accomplish this? Here is my code: <label>T ...

"Utilizing Google Charts DataTable to easily adjust column number based on data dynamics

Struggling with managing JavaScript objects... Currently, I am working on generating a Google Chart based on user selections. The process involves two multi-select lists that construct an object as shown below: $('option:selected', $('#slC ...

Response Looping Function

I am struggling with looping and storing data in an array. /** Model for displaying response*/ export class ResultsData { id: number, name: string, startDate: string, endDarte: string, startTime: string, ...

Create a regular expression in Javascript that only matches strings that do not contain any periods

Struggling with setting up an express route for localhost:3000/test and utilizing regex to handle specific URL patterns. Need assistance combining regex with Express params functionality. router.get('/test/:path[\s^.]*$', function () { ...

Angular: facing difficulty displaying static html pages on server, although they render correctly when run locally

Within my Angular project, I have stored a few static html files (specifically sampleText.html) in the src/assets/html folder. In one of my components, I am attempting to fetch and display this file. The following code is being used for this purpose. Every ...

Having trouble getting Material-UI classes to work with external SVG icons?

I recently crafted a Material-UI persistent drawer that contains a list item component designed to alter the icon color upon user interaction. However, my styling adjustments only seem to apply to Material-UI icons and not external SVG ones. If you'r ...

Implementing a versatile free text filter with numerous values using MUI

I am currently working on incorporating a free text filter view using MUI. Although the Autocomplete component already has this feature (when the 'multiple' attribute is enabled), I am looking to input free-form text instead of selecting from pre ...

Having trouble receiving a response from an API built using Express.js and SQL Server

Currently, I am in the process of learning how to create an API using Node and Express.js. I came across a step-by-step guide that has been very helpful. You can check it out here. I've followed the instructions provided and created a similar version ...

Adding properties with strings as identifiers to classes in TypeScript: A step-by-step guide

I am working with a list of string values that represent the identifiers of fields I need to add to a class. For instance: Consider the following string array: let stringArr = ['player1score', 'player2score', 'player3score' ...

Can Node.js be utilized to generate an XLS excel file while specifying the cell type?

I've noticed that many libraries have the capability to export to XLSX (Excel > 2007) or CSV formats, but not in XLS (which I assume is due to its outdated file format). I came across something where if you use fs.createOutputStream("filename. ...

Checking the length of user input with JavaScript

To ensure that the user enters at least 4 letters in a text box and show an error if they don't, I need help with the following code. It is partially working but currently allows submission even after showing the error message. I want to prevent subm ...

Creating synchronicity in your code within the useEffect hook

Is there a way to ensure that my function is fully completed before moving on, even though it's not recommended to add async to useEffect? Take a look at this code snippet: useEffect( () => { const RetrieverDataProcess = async () => ...

Retry an Ajax request immediately after a timeout without having to wait for the full

I am attempting to resend an AJAX request every 5 seconds if there is an issue, but when I simulate an offline connection with Chrome, the AJAX request doesn't wait 5 seconds between each attempt and keeps getting called continuously. What could be c ...

Utilize javascript/jquery for transforming HTML table data to JSON

Whenever I click the "+" button, my table rows are dynamically generated. After populating the fields and clicking the submit button next to "+", the JSON data is displayed in the console, as shown in the image below. While generating the JSON data, I aim ...

Send back alternate HTML content if the request is not made via AJAX

Last time I asked this question, I received several negative responses. This time, I will try to be more clear. Here is the structure of a website: Mainpage (Containing all resources and scripts) All Other pages (HTML only consists of elements of that ...