callback element doesn't show anything in console [duplicate] - javascript

This question already has answers here:
Puppeteer log inside page.evaluate
(13 answers)
Closed 1 year ago.
Here, I am trying to get each players runs and matches using player-URL.
When I passes selector within page.$$eval method and in callback element when I console it,I got nothing in it.
const stats = await page.$$eval(
"div.score-top.sp.text-center > div.container > div.match-summary > div.row > div.col-sm-12 > div.match-in-summary > div.row > div.col-sm-5 > div.matches-runs-wickets > ul.list-inline ",
(elements) => {
console.log("elements", elements);
return elements.map((match) => {
return (obj = {
matches: match.querySelector(" li:nth-Child(1) >span").innerText,
runs: match.querySelector("li:nth-Child(2) > span").innerText,
});
});
}
);
return stats;
}
but when I map over the callback element and return the object then I am getting runs and matches in stats variableThe code detail is mentioned here.

Everything that you console.log in eval function will be displayed in browser's console. See the console of the browser that you have opened and there you will see the logs that you are trying to print.

In your example console.log is happening not on the node.js side, but inside of a headless browser's console. You can see messages if you launch puppeteer with headless: false option.
And if you'd like to receive such console messages in terminal, see this answer.

Related

Puppeteer: How do I get the value from the loop?

I need to load the code on the page that will check the value of one element in a loop and after it becomes necessary, then return this value.
How can I do this correctly?
Your question is really vague, so I'm note sure if I understood correctly, but you may be looking for page.evaluate(). With this function you can execute code on browser context and then return some information.
Ex.:
var output = await page.evaluate(() => {
let urlSelector= '#someId > tbody > tr:nth-child(1) > td:nth-child(2) > a';
let desiredUrl = document.querySelector(urlSelector).href;
console.log(desiredUrl);//print the url in browser console
return desiredUrl;
});
console.log(output);//prints the url in node console
In this example I executed the code in browser context and returned a desired url to the "output" variable in my script.

How do I make this code work in Firefox? Currently, it only works in Chrome [duplicate]

This question already has an answer here:
then() callback firing before promise is resolved in node.js [duplicate]
(1 answer)
Closed 2 years ago.
I was making a simple todolist app and everything else works fine but my delete item code is only working in chrome and no other browser. I even tried it in latest firefox version but it just doesn't seem to work and I have no idea why.
Here's the code:
function removeTask(e) {
if (e.target.classList.contains("del")) {
//e.target.parentElement.remove();
let item = e.target.parentElement.childNodes[0].textContent
.replace(/[\n\r]+|[\s]{2,}/g, " ")
.trim();
console.log(item);
let url = `/items/${item}`;
http
.delete(url)
.then(reloader())
.catch((err) => console.log(err));
function reloader() {
location.reload();
}
}
}
The above code looks fine but whenever I try deleting an item, it works in chrome but is not working in firefox (latest version) and edge. I haven't checked on other browsers.
(Update: Sometimes it deletes an item but when I try deleting another item, it does not work)
http
.delete(url)
.then(reloader())
.catch((err) => console.log(err));
Here you call reloader() immediately and pass its return value to .then(). I think instead, you want to reload the page after the http.delete() request returns with a response. To do this, pass the function to .then instead of calling it first:
http
.delete(url)
.then(reloader)
.catch((err) => console.log(err));
Since reloader() just calls location.reload(), you can get rid of reloader() like this:
http
.delete(url)
.then(location.reload)
.catch((err) => console.log(err));

How to fetch output from console.log [duplicate]

This question already has answers here:
Capturing javascript console.log? [duplicate]
(2 answers)
Closed 4 years ago.
I have been seeing in some questions on Stack Overflow that there is examples, example code or snippets. Such as the one below:
console.log(1, 2, 3)
By running the code snippet above you'll see something like this:
I am currently working with something in node.js that also requires to fetch the output from console.logs. I find it fascinating that Stack Overflow is able to do this, whilst I don't even have a single clue how they did this.
I would be very thankful if someone could send me a link to where I can read and learn about how to fetch data form the console API.
Cheers,
Richard
P.S. If someone could edit this post to display the image, I'd be very thankful.
Edit
The project that I'm working on is an Electron app. It uses both the node.js process and the Electron BrowserWindow.
It uses a logger that I'm working on wich needs to fetch data from console.log
Some of the use cases might look like this:
console.log('%d is cool', User.firstName)
// => "Jason is cool"
or
console.log('User ID:', User._id)
// => A5FFE
or
console.log('%cUser connected!', 'color: #00FF00')
// => User connected!
// In green text.
You can overwrite window.console.log with your own function to achieve such an effect. For example:
const oldConsoleLog = console.log.bind(console);
console.log = (...params) => {
const textToDisplay = params.map(param =>
typeof param === 'object'
? JSON.stringify(param)
: param
);
document.body.appendChild(document.createElement('div'))
.textContent = textToDisplay;
oldConsoleLog(...params);
};
console.log('foo');
console.log('bar baz');
console.log({ prop: 'value' });
.as-console-wrapper {
height: 60%
}
In nodejs, console.log just formats the data you pass to it and then writes it to process.stdout which is a stream that goes to your commandline window. To intercept that, you can just listen for events on that stream:
process.stdout.on("data", chunk => {
// Do what you wanna do
});

JavaScript only works with a breakpoint set in browser debugger [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 6 years ago.
I have a basic function in JavaScript that simply takes some pre-set values and puts them onto the screen by the use of a pre-made function. When I breakpoint the first line of what it is I'm doing, the page loads fine, as expected, but as soon as I remove that breakpoint, none of the information is set. and the page is blank.
this.QuizSelection = function () {
// Fill the ID's with the right info
app.SetBackground('head', this.HeroImage);
console.log('1 ' + this.HeroImage);
app.LoadInnerHTML('breadcrumbs', 'Home / ' + this.Title);
app.LoadInnerHTML('quizSelectionTitle',this.Title);
console.log('2 ' + this.Title);
app.LoadInnerHTML('quizSelectionIntro',this.Introduction);
console.log('3 ' + this.Introduction);
// Show the Quiz Selection and Heading
app.ShowSection('head');
app.ShowSection('quizSelection');
console.log('Quiz Selection');
}.bind(this);
The functions inside that (SetBackground and LoadInnerHTML) are just small one line functions that change the inner html and the set a background image.
// Change Inner HTML
this.LoadInnerHTML = function (id, html) {
var d = document.getElementById(id);
d.innerHTML = html;
}
// Set Background Image
this.SetBackground = function (id, image) {
document.getElementById(id).style.backgroundImage = 'url(image)';
}
I can't understand why it wouldn't work when the breakpoint isn't on. Clearly it does work, because everything is fine with the breakpoint on, but then when it's off the result I get output to the console is:
1
2
3 undefined
Quiz Selection
You have a race condition.
The act of hitting a breakpoint makes your code wait for the async JSON load to complete. Without the breakpoint, the code trying to read the JSON is executing before the JSON has actually loaded.
See How do I return the response from an asynchronous call? for how to fix this issue.
You have console.log statements in your code. When the debugger is not on, console object does not exist (this is true for IE not for Chrome to the best of my knowledge), thus your javascript code execution fails.

Access DOM from popup.js | Chrome Extension

I'm trying to make a Chrome Extension that will take some of the contents of a page (The inner HTML of a <span> with id="productTitile") I then would need to take that value and put it into a field in my popup.html.
I have tried this:
document.getElementById('input_87').value = chrome.tabs.executeScript({
code: 'document.getElementById("productTitle").innerHTML'
});
But it just returns undefined into the field. I then ran document.getElementById("productTitle").innerHTML in the console in the parent page, and it gave me the expected value, but when I ran the whole code in console of the popup extension, it again returned undefined.
What am I doing wrong?
First off, as Haibara Ai says, chrome.tabs.executeScript is asynchronous - it doesn't return anything (and doesn't do anything immediately).
A good source on this in general is this question: How do I return the response from an asynchronous call? (spoiler: you can't)
If you look at the docs (which, by the way, should be your first unconditional reflex), you'll see that it has a callback and if you read the above question you'll understand it's your only option. However, there are 2 additional complications:
The callback gets an array of results. That happens because executeScript can, optionally (with allFrames: true or frameId specified), run in subframes. So you'll need to use the first element of the results array:
chrome.tabs.executeScript({
code: 'document.getElementById("productTitle").innerHTML'
}, function(results) {
document.getElementById('input_87').value = results[0];
});
The call to executeScript can fail - for example, when the page is not scriptable regardless of permissions, such as the Chrome Web Store. It's wise to check that you actually got the result before using it:
chrome.tabs.executeScript({
code: 'document.getElementById("productTitle").innerHTML'
}, function(results) {
if (chrome.runtime.lastError) {
// Couldn't execute the script at all
} else if (typeof results[0] === "undefined") {
// Couldn't find what we wanted
} else {
// Everything is fine
document.getElementById('input_87').value = results[0];
}
});

Categories

Resources