Is there any way to output js errors using headless chrome?
For example, this site https://labs.observepoint.com/ has this js error: Uncaught SyntaxError: Unexpected token ! and I need to log it in headless chrome
This is what I tried:
Start headless chrome with: google-chrome --headless --enable-logging --v=1 --remote-debugging-port=9222
And then run this code:
const CDP = require('chrome-remote-interface');
CDP((client) => {
// extract domains
const {Network, Page} = client;
// setup handlers
Network.requestWillBeSent((params) => {
console.log(params.request.url);
});
Page.loadEventFired(() => {
client.close();
});
// enable events then start!
Promise.all([
Network.enable(),
Page.enable()
]).then(() => {
return Page.navigate({url: 'https://labs.observepoint.com/'});
}).catch((err) => {
console.error(err);
client.close();
});
}).on('error', (err) => {
// cannot connect to the remote endpoint
console.error(err);
});
But I don't know where the browser errors are logged
Try to use --enable-logging=v=1 in your command line. More information you can find here: enable-logging.
Related
I'm very new to Cypress.js.
Problem statement:
I'm running cypress in headless mode (Chrome) and one of the API calls is failing with uncaught exception. However, when I manually visit the url it works fine!
I'm not sure if its because of some SSL certificate issue or what's happening. Everything works normally when I visit the url in my chrome/firefox/safari.
Follow-up questions:
My recording shows it's uncaught exception but I don't know why / what is failing.
How do I log my failing network requests into a log file to see what the actual error is?
Am I missing any configuration?
This is my configuration:
cypress/plugins/index.js
module.exports = (on, config) => {
// `on` is used to hook into various events Cypress emits
// `config` is the resolved Cypress config
on('before:browser:launch', (browser = {}, launchOptions) => {
launchOptions.args.push('--ignore-urlfetcher-cert-requests')
launchOptions.args.push(`--ignore-certificate-errors`)
launchOptions.args.push(`--unsafely-treat-insecure-origin-as-secure=http://localhost:9999`)
return launchOptions
})
}
Cypress.json
{
"reporter": "junit",
"reporterOptions": {
"mochaFile": "cypress/results/helltool.xml",
"toConsole": true
},
"defaultCommandTimeout": 20000,
"pageLoadTimeout": 20000,
"responseTimeout": 20000,
"chromeWebSecurity": false
}
Sample Test
Cypress.on('uncaught:exception', (err, runnable) => {
console.log(`CYPRESS uncaught exception FLOW:::: ${err}`);
debugger;
return false;
});
describe('Flow Sanity Tests', () => {
before(() => {
// We need to login before we can do anything
// TODO: Abstract this inside Looker.explore
cy.login('admin', { flow: true })
})
it('Test to check Flow exists and run it', () => {
// Some test to execute after login
})
Login flow (in support/commands.js)
Cypress.Commands.add('login', (userType, options = {}) => {
const types = {
admin: {
email: 'demo#demo',
password: 'thisisademopassword',
},
}
// Go to login page
cy.goTo('login', options)
// grab the user
const { email, password } = types[userType]
cy.wait(2000)
// type the stuff.
cy.get('#login-email', { timeout: 30000 }).should('exist').debug()
cy.get('#login-email').type(email)
cy.get('#login-password').type(password)
cy.get('#login-submit').click()
})
Execution:
npm run cypress:run -- --spec "cypress/integration/flow/demo.spec.js"
--browser chrome
while deploying pub-sub code on firebase i'm getting following error :
ERROR: (gcloud.functions.deploy) OperationError: code=3, message=Function failed on loading user code. This is likely due to a bug in the user code. Error message: Code in file index.js can't be loaded.
Is there a syntax error in your code?
Detailed stack trace: /srv/node_modules/#google-cloud/pubsub/build/src/pubsub.js:527
async *listSchemas(view = schema_1.SchemaViews.Basic, options) {
^
I'm not getting why this error is occurring.
following is the code:
exports.publish = async (req, res) => {
if (!req.body.topic || !req.body.message) {
res.status(400).send('Missing parameter(s); include "topic" and "message" properties in your request.');
return;
}
console.log(`Publishing message to topic ${req.body.topic}`);
const topic = pubsub.topic(req.body.topic);
const messageObject = {
data: {
message: req.body.message,
},
};
const messageBuffer = Buffer.from(JSON.stringify(messageObject), "utf8");
try {
await topic.publish(messageBuffer);
res.status(200).send("Message published.");
} catch (err) {
console.error(err);
res.status(500).send(err);
return Promise.reject(err);
}
};
I'm going to guess that this function is set to use the Node 8 runtime, since support for async iterators was added in Node 10. The Pub/Sub library has only supported Node 10 and above since 2.0, so bumping the runtime version on the Firebase function should help:
https://firebase.google.com/docs/functions/manage-functions#set_nodejs_version
Unfortunately I don't have enough points to ask for more details on the original question, but hopefully that helps!
Trying to make an Progressive Web App, using ASP.NET Core 2.1, using Nuget: WebEssentials.AspNetCore.PWA.
My serviceworker and manifest gets displayed in the Chrome Dev Tools, but when I hit the "Add to homescreen" nothing happens except displayed error on computer, and on phone the load banner on top is stuck loading.
The error:
Site cannot be installed: the page has requested the banner prompt be
cancelled
I couldn't seem to find anything on this error, so hope you guys can help me out. Thanks in advance.
ServiceWorker:
self.addEventListener('install', async event => {
const cache = await caches.open(CACHE_NAME);
cache.addAll(urlsToCache).catch(err => console.log('An error occured: ', err));
});
self.addEventListener('fetch', event => {
const request = event.request;
const url = new URL(request.URL);
if (url.orgin === location.orgin) {
event.respondWith(cacheFirst(request));
} else {
event.responseWith(networkFirst(request));
}
});
async function cacheFirst(request) {
const cachedResponse = await caches.match(request);
return cachedResponse || fetch(request);
}
async function networkFirst(request) {
const cache = await caches.open('wportal-dynamic-v1');
try {
const res = await fetch(request);
cache.put(request, res.clone());
return res;
} catch (exception) {
console.log('An error occured in networkFirst: ', exception);
return await cache.match(request);
}
}
Found the solution..
var deferredPrompt = null;
window.addEventListener('beforeinstallprompt', (e) => {
e.preventDefault(); // Prevent Chrome 67 and earlier from automatically showing the prompt
deferredPrompt = e;
});
<button onclick="deferredPrompt.prompt();">Click me to install pwa</button>
This question might have been asked by many people, but I have no luck to get answer from researching.
My ultimately plan is running a web app with Web Bluetooth API in smartphone with FLIC button to control audios to play. One click, play one audio.
I'm testing the program in my MAC laptop with my iPhoneX first, because I'm thinking if I can get both of them connected, then when I run the web app in smartphone, then I can connect to the FLIC button.
However, I got this error.
Something went wrong. NotSupportedError: GATT Error: Not supported.
Am I missing something? I saw someone mentioned iPhone cannot connect Latop, hopefully this is not true
Below is the code:
$("#bluetooth").on("click", function(){
const controlServiceUUID = '00001805-0000-1000-8000-00805f9b34fb'; // Full UUID
const commandCharacteristicUUID = '00002a0f-0000-1000-8000-00805f9b34fb'; //
var myCharacteristic;
navigator.bluetooth.requestDevice({
acceptAllDevices: true,
optionalServices: [controlServiceUUID]
})
.then(device => {
console.log("Got device name: ", device.name);
console.log("id: ", device.id);
return device.gatt.connect();
console.log("Here");
})
.then(server => {
serverInstance = server;
console.log("Getting PrimaryService");
return server.getPrimaryService(controlServiceUUID);
})
.then(service => {
console.log("Getting Characteristic");
return service.getCharacteristic(commandCharacteristicUUID);
})
.then(characteristic => {
// 0x01,3,0x02,0x03,0x01
myCharacteristic = characteristic;
return myCharacteristic.startNotifications().then(_ => {
log('Notifications started');
myCharacteristic.addEventListener('characteristicvaluechanged', test);
});
})
.catch(function(error) {
console.log("Something went wrong. " + error);
});
function test(event) {
if (myCharacteristic) {
myCharacteristic.startNotifications()
.then(_ => {
console.log("Notification stopped!");
})
.catch(error => {
console.log("Argh!" + error);
});
}
}
});
Web Bluetooth API is only available on ChromeOS and Android 6 or later with flag option.
(https://developer.mozilla.org/en-US/docs/Web/API/Web_Bluetooth_API)
Different platforms are at different points in implementation. I have been using this repo for updates on the status of the API:
WebBluetoothCG/web-bluetooth
Note the lack of support for ios
Not sure if this fixes your problem (i'm working on muse eeg), but one "hack" to get rid of this error is to wait some time (e.g. 500ms) after each characteristic write. Most platforms don't support write responses yet and writing multiple commands in parallel will cause this error.
https://github.com/WebBluetoothCG/web-bluetooth/blob/master/implementation-status.md
Is your command characteristic UUID filled in incorrectly? Try replacing it with one that can be written?
const controlServiceUUID = 0xfff0; // Full UUID
const commandCharacteristicUUID = 0xfff4; //
Does anyone have a proper example on how to configure BrowserMobProxy with WebDriverIO? This is so I can capture network traffic. I previously had it working with WebDriverJS, which is essentially a deprecated version of WebDriverIO.
You can use the below code to do that. Make sure your browsermob proxy and selenium server is running. Then copy paste below code in a test.js file and put it in webdriverio installed folder. From cmd go to that folder and run node test.js . stuff.har should be generated where test.js is located.
var Proxy = require('browsermob-proxy').Proxy
, webdriverio = require("./node_modules/webdriverio/")
, fs = require('fs')
, proxy = new Proxy()
;
proxy.cbHAR('search.yahoo.com', doSeleniumStuff, function(err, data) {
if (err) {
console.error('ERR: ' + err);
} else {
fs.writeFileSync('stuff.har', data, 'utf8');
}
});
function doSeleniumStuff(proxy, cb) {
var browser = webdriverio.remote({
host: 'localhost'
, port: 4444
, desiredCapabilities: { browserName: 'firefox', seleniumProtocol: 'WebDriver', proxy: { httpProxy: proxy } }
});
browser
.init()
.url("http://search.yahoo.com")
.setValue("#yschsp", "javascript")
.submitForm("#sf")
.end().then(cb);
}
If you just want to capture the network traffic, then there is one more way to do it.
Webdriverio allows you to use Chrome Dev Tools Protocol.
Please read webdriverio blog
This is one of the examples on how to use chrome dev tools along with webdriverio, do let me know in case you need more help.
const { remote } = require('webdriverio')
let browser;
(async () => {
browser = await remote({
automationProtocol: 'devtools',
capabilities: {
browserName: 'chrome'
}
})
await browser.url('https://webdriver.io')
await browser.call(async () => {
const puppeteerBrowser = browser.getPuppeteer()
const page = (await puppeteerBrowser.pages())[0]
await page.setRequestInterception(true)
page.on('request', interceptedRequest => {
if (interceptedRequest.url().endsWith('webdriverio.png')) {
return interceptedRequest.continue({
url: 'https://user-images.githubusercontent.com/10379601/29446482-04f7036a-841f-11e7-9872-91d1fc2ea683.png'
})
}
interceptedRequest.continue()
})
})
// continue with WebDriver commands
await browser.refresh()
await browser.pause(2000)
await browser.deleteSession()
})().catch(async (e) => {
console.error(e)
await browser.deleteSession()
})
Since I had no luck solving this problem using browsermob proxy (AFAIK it wasn't updated in a while)
I created a small npm module to capture selenium tests as HAR files - https://www.npmjs.com/package/har-recorder
I took #Raulster24 suggestion and implemented it using the Chrome Dev Tools Protocol - https://github.com/loadmill/har-recorder/blob/master/index.js