Puppeteer: Launch Chromium with "Preserve log" enabled - google-chrome-devtools

There is this handy feature in DevTools that you are able to preserve log (so it does not clear the content of the console nor the network tab etc. on page reloads / navigation).
At the moment my hand needs to be as fast as a lightning to click the checkbox during debugging if I don't want to miss a thing. I've already looked for corresponding chrome launch flags on peter.sh without a luck.
Is there a way to launch chromium with this feature enabled? Can it be applied with puppeteer?
My set up is so far:
const browser = await puppeteer.launch({ headless: false, devtools: true })
Edit
Thanks to the comment of #wOxxOm I was able to enable it, but the solution requires three additional dependencies on the project: puppeteer-extra, puppeteer-extra-plugin-user-preferences and puppeteer-extra-plugin-user-data-dir.
I would be interested in a solution without extra dependencies, exclusively in puppeteer.
user-preferences example:
const puppeteer = require('puppeteer-extra')
const ppUserPrefs = require('puppeteer-extra-plugin-user-preferences')
puppeteer.use(
ppUserPrefs({
userPrefs: {
devtools: {
preferences: {
'network_log.preserve-log': '"true"'
}
}
}
})
)

I've had some success without any extra packages:
Launch and close a Browser instance for the sole purpose of generating a new user data directory. Ideally you have provided your own path to it.
Locate the Preferences file (it's a JSON file), read it and write to devtools.preferences.
Relaunch a Browser (using the user data directory created in step 1)
Here's some code to get you started:
I've used the official puppeteer-core package so that I can use my local installation of Chrome which is why I provided the executablePath option. You don't need this if you use the full puppeteer package.
const pp = require('puppeteer-core');
const fs = require("fs");
const run = async () => {
const opts = { executablePath: "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"
, devtools: true
, userDataDir: "/tmp/pp-udd"
, args: ["--auto-open-devtools-for-tabs"]
};
// open & close to create the user data directory
let browser = await pp.launch(opts);
await browser.close();
// read & write Preferences
const prefs = JSON.parse(fs.readFileSync("/tmp/pp-udd/Default/Preferences"));
prefs.devtools.preferences['network_log.preserve-log'] = '"true"';
fs.writeFileSync("/tmp/pp-udd/Default/Preferences", JSON.stringify(prefs));
// relaunch with our own Preferences from our own user data directory
browser = await pp.launch(opts);
let page = await browser.newPage();
await page.goto("https://stackoverflow.com/q/63661366/1244884");
};
run();
And here's a screencast:
The first launch is the "launch & close" of step 1
Then there's the second launch that goes to this question ;) with the DevTools open and the "Preserve log" option checked right from the start.

Related

Protractor file upload with Saucelabs (Chrome 90) redirected to "data:text/html,<html></html>" after upload, works locally but not on Saucelabs

I am using protractor for a Node.js application with Chrome, in one test case I have to upload image and then click add/update button. The test case is working perfectly on my machine, but on Saucelabs it cant interact with the button after the image is uploaded. If I don't upload image its able to find button and click on it but when using with image upload it doesn't.
I have printed the current URL after image upload and it shows
"data:text/html,", whereas in the Saucelabs video I can see previous page.
Approaches I have tried
Tried to print all available handles and it only prints 1 handle i.e.
"handles are [chrome 90.0 Windows 10 #01-1]
CDwindow-B29A329D03022E36745F1A844177FAA8"
Print Current URL "data:text/html,"
Code
const remote = require('selenium-webdriver/remote');
browser.driver.setFileDetector(new remote.FileDetector());
// absolute path resolution
const path = require('path');
const fileToUpload = './Test_Images/' + imageName;
const absolutePath = path.resolve(__dirname, fileToUpload);
console.log('path is ', absolutePath);
// Find the file input element
const fileElem = element(by.css('input[type="file"]'));
//upload image
await browser.sleep(2000);
fileElem.sendKeys(absolutePath);
console.log('\n Image Uploaded for report');
//print current url after image upload
const currentUrl = (await browser.getCurrentUrl()).toString();
console.log('\n Current URL', currentUrl);
await browser.sleep(2000);
//get all handles
browser.getAllWindowHandles().then(function (handles) {
for (const handle of handles) {
console.log('\n\nhandles are\n', handle.toString());
}});
//click on the submit button
await adminReportsPage.createReportButton.click();
console.log('Report Submit button Clicked ');
The reason why this fails is because a remote machine in the cloud, as with Sauce Labs, does not has access to your local file system and your local machine has.
I'm not 100% sure if Protractor has a workaround for this, but with a framework like for example WebdriverIO, you have the option to use a method like uploadFile. That method will only work on Chrome and will translate the file to a base64 string so you can upload it form your local machine to the remove machine.
A working example can be found here
Last but not least, keep in the back of your mind that Protractor is deprecated and with the upcoming release of Selenium 4 you can't use it anymore because it doesn't support W3C. Also check the Protractor repository for more information.
#wswebcreation I have found a solution, it worked by changing the
const fileElem = element(by.css('input[type="file"]'));
to
const fileElem = browser.driver.findElement(by.css('input[type="file"]'));

Clear Shared Preferences When the App is Uninstalled?

I'm using shared preferences to store the current user's name, avatar, and a boolean for whether the user is logged in. Uninstalling the app seems to lead to a problem when re-installing. It appears related to shared preferences because when I log out and log back in the problem goes away. I suspect the shared preferences file is corrupted somehow and this triggers problems all over my app.
So is there a way I can either clear or delete the shared preferences file upon uninstall?
If it helps, here's the code for logging out;
Future<void> logOutSocial() async {
try {
socState();
await socialLogin.logOutFacebook();
await socialLogin.logOutGoogle();
await socialLogin.logOutTwitter();
currentname = "Anonymous";
currentavatar = "https://example.com/default.jpg";
currentlogged = false;
currentuserid = "0";
await savePreferences(
currentname: "Anonymous",
currentavatar: "https://example.com/default.jpg",
currentlogged: false,
);
notifyListeners();
} catch (e) {
print(e);
}
}
Android
There are two options:
Disabling Auto Backup
beginning from API level 23 (Android 6) there Auto Backup is set to true by default. You need to edit AndroidManifest.xml file and set the boolean value of android:allowBackup. In your case it should be something similar to:
<manifest ...>
...
<application android:allowBackup = "false">
</application>
</manifest>
More info about AutoBackup
Declare what you want to store
Everything is described quite clearly in the documentation.
iOS
Check this out.
Owczar's suggestion that I changed package name during development seemed to be my problem. But I decided to use Hive as a slot in replacement for Shared Preferences and that solved the issue as the Shared Preferences file is no longer neccessary.

Is it possible to make the devtool status off when using Puppeteer?

is it possible to make the devtool status off when using Puppeteer?
because there are some websites that protect their pages from being inspected using devtool, so it can not be accessed using Puppeteer.
I opened this url https://jsbin.com/cecuzeb/edit?js,output to check devtool status
const browser = await puppeteer.launch({
headless: false,
devtools: false,
});
const page = await browser.newPage();
await page.goto('https://jsbin.com/cecuzeb/edit?js,output');
is there any way to make this status off?
The answer below is rather a theoretical version to prevent detection by normal dev tools detection using /./.toString method based on the provided jsbin link on main question.
Stop all intervals of page. Since most devtool detection libraries are simply running the interval check, we can stop them.
(function(w){w = w || window; var i = w.setInterval(function(){},100000); while(i>=0) { w.clearInterval(i--); }})(/*window*/);
Stop console.clear, if there are no console.clear running, then you won't have problem with the console getting cleared without your permission. Also stop printing "%c" or any other clearing characters.
console.clear = console.log = console.warn = console.error = () => {};

Copy Debug Console to the clipboard

I'm debugging a Node.js app in Visual Studio Code 1.0.0 and want to copy the entire contents of the Debug Console to the clipboard. After drag-selecting the Debug Console contents, Edit->Copy only copies the visible parts instead of the entire selection.
Any ideas how to copy the entire selection? I'd also be okay saving the contents to a file.
It only took 13 months (!) but a recent update has added a "Copy All" command to the context menu.
Apparently this is not possible yet. See https://github.com/Microsoft/vscode/issues/2163 for details.
I would prefer to save the response(long one) to a file, which would help me with debugging or copying to clipboard. VS Code, debug console output doesn’t prints long output.
const fs = require('fs');
async function getData(params) {
try {
const data = await callApi(params);
fs.writeFileSync("/Users/response.json", JSON.stringify(data, null, 2)); // saves file in local folder (pretty prints the data)
res.status(200).json(data);
} catch(err) {
console.log('Error :', err);
res.status(400).send('Something went wrong while fetching data');
}
}
I guess I am very late on this but the easy way is to create a log file when you run the node command in the terminal. Something like:
PS C:\temp\myprojectfolder>node product.js >product.log
This will create the log file and you can easily copy all the content. This also has an added benefit. You won't lose the log even if you accidentally close the terminal window.
You can select from start window and drag the mouse over the textbox at bottom (http://screencast.com/t/Clz24yCo )

How do you make the Chrome Developer Tools only show your console.log?

It adds logs when plugins say something. It adds logs when it gets anything from the cache manifest. It logs HTTP information sometimes.
My 1 little log gets flooded by 10,000 logs I don't need or want.
Use only in development:
(function(){
var originalConsole = window.console;
window.console = {};
window.console.log = window.console.debug = window.console.error = function(){};
window.myLog = function() {
originalConsole.log.apply(originalConsole, arguments);
};
}());
This will save a local copy of the original window.console object.
It will change the original window.console object to use empty functions.
And finally it will define a global myLog function which will use the local copy of the original window.console to actually log stuff.
This way all the other code will use the useless console.log() and your code could use myLog().
on the Console tab select No info on the left Hand I have attached a screenshot here
You should update to the google chrome latest version