WebSocket does not connect to a specific host until Chromium is restarted - google-chrome

we are trying to debug an issue with Chromium (happens in Chrome, Edge, Brave), where it sometimes gets to a state where it does not open a WebSocket to a specific host.
We can see in console logs that it is trying to open the socket, but it never opens the connection. It fails with 1006 error. The same happens in new tabs and in new windows. The behaviour disappears after the browser is restarted or when an incognito tab is used.
There are no HTTP upgrade requests on the server and also the connection does not show up as WebSocket in chrome dev tools. We do not have much else to go on. Any suggestions on what we could try to debug the problem?

I tried to test the web socket with the MS Edge (chromium) Version 83.0.478.58 and Google Chrome Version 83.0.4103.116
In my test, both the Chromium browser works well without 1006 error.
Here is the test code:
<!DOCTYPE html>
<meta charset="utf-8" />
<title>WebSocket Test</title>
<script language="javascript" type="text/javascript">
var wsUri = "wss://echo.websocket.org/";
var output;
function init()
{
output = document.getElementById("output");
testWebSocket();
}
function testWebSocket()
{
websocket = new WebSocket(wsUri);
websocket.onopen = function(evt) { onOpen(evt) };
websocket.onclose = function(evt) { onClose(evt) };
websocket.onmessage = function(evt) { onMessage(evt) };
websocket.onerror = function(evt) { onError(evt) };
}
function onOpen(evt)
{
writeToScreen("CONNECTED");
doSend("WebSocket rocks");
}
function onClose(evt)
{
writeToScreen("DISCONNECTED");
}
function onMessage(evt)
{
writeToScreen('<span style="color: blue;">RESPONSE: ' + evt.data+'</span>');
websocket.close();
}
function onError(evt)
{
writeToScreen('<span style="color: red;">ERROR:</span> ' + evt.data);
}
function doSend(message)
{
writeToScreen("SENT: " + message);
websocket.send(message);
}
function writeToScreen(message)
{
var pre = document.createElement("p");
pre.style.wordWrap = "break-word";
pre.innerHTML = message;
output.appendChild(pre);
}
window.addEventListener("load", init, false);
</script>
<body>
<h2>WebSocket Test</h2>
<div id="output"></div>
</body>
</html>
Reference:
Web socket echo test
Try to check the security settings of the browsers and also confirm that you are trying to connect using a secure connection.
I found that 1006 is a special code that means the connection was closed abnormally (locally) by the browser implementation.
I suggest you can check WebSocket.onerror(evt) to get more details about the error.
Helpful thread link:
getting the reason why WebSockets closed with close code 1006
If there is more information then you can try to provide us that may help to narrow down the issue.

I observed exactly the same symptom (not sure about the error code) in Brave (but not in Chrome) during 2020 ... it was a constant issue... but since then it didn't happen almost at all since JAN 2021... except last week (in APR 2021) it happened again (in Brave).
Did anyone else notice the issue still being present from time to time? Or maybe it's a new bug, similar but more rare...
Exactly the same behaviour, socket doesn't reconnect except in incognito or after browser restart.

We have been facing this exact issue where Websocket's upgrade requests never reach the server even though the network inspect tab shows that the request has been fired. No amount of refreshing or new tabs help until we switch over to Chrome. The issue is intermittent and has become impossible to debug but nonetheless our users keep reporting infinite loading bars due to the un-connected websocket.
I went through capturing network logs using chrome://net-exports and viewing it on the net-export viewer and the only time I could capture the logs for the issue, I noticed the browser only trying an IPv6 address and not the IPv4 address. (when our servers don't even have one)
Would it be prudent to engage Brave or Chromium team in this? Anyone ever found concrete repro steps for this?

Related

Google login fails with HTTP error 400 saying "Sorry, something went wrong there. Try again."

Description/background
I had set up a script which opened a Google site of our company in Google Chrome (not headless) and did some automated work on that page. The login information had to be refreshed occasionally what for I manually logged in. That had been working perfectly the last couple of months until last week. Today I noticed that I get the above mentioned error message as a result of a server response with HTTP status 400 upon entering my Gmail address and clicking the Next button.
Steps to reproduce
Puppeteer version: 2.0.0
Platform / OS version: Windows 10
URLs (if applicable): https://sites.google.com/...
Node.js version: v12.13.0
What steps will reproduce the problem?
Run a Puppeteer script to open a Google Site which requires login.
(async () => {
try {
const browser = await puppeteer.launch({headless: false, userDataDir: "<ProfileDirectory>"});
const pageLogin = await browser.newPage();
await pageLogin.goto('https://sites.google.com/...', {waitUntil: 'networkidle2'});
...
await browser.close();
}
catch (error) {
console.log(error.stacktrace);
}
})();
Manually enter Gmail address and click Next.
Get error message "Sorry, something went wrong there. Try again." as a result of a server response with HTTP status code 400.
Update:
Manually opening Chrome (same userDataDir) and the respective Google site still works as usual.
Recommend to use playwright/puppeteer + Firefox. It seems like google adds something into chrome so they can detect the browser is automated or not
One of the comments on this post mentions that Google tries to block logins with Puppeteer, Selenium etc. this might be why you are getting a 400 error.
One of the recent comments on the aforementioned post, links a gist with some example code that might still work, haven't tried it though.
While I was doing research on Puppeteer for Firefox, I noticed that (1) Puppeteer downloads its own local Google Chrome binaries it is executing and (2) my installed Puppeteer version 2.0.0 was outdated. Meaning, the browser actually used by Puppeteer was probably also outdated. The solution was as easy as to update Puppeteer to the latest version 2.1.1.

Wake-lock works in browser, but not as PWA

I have a web app that uses wake lock (see below) - I have registered the origin trial and added the code to my index.html. - see https://lucid-franklin-4016c2.netlify.com/
When I load the page in the latest version of Android Chrome the phone stays awake, and the text-to-speech messages I use for this running app work fine.
I've also set it up as a PWA (service worker, manifest,... - all good in lighthouse). However, after "add page to home screen" and loading the PWA from there the phone does go to sleep. It continues to count time and can play sound files in the background but text-to-speech is deactivated.
Is this expected behaviour?
My key need is text-to-speech rather than to keep the phone awake as such, as geolocation seems to work while the phone is asleep anyway. Is there something else I could be doing?
// The wake lock sentinel.
let wakeLock = null;
// Function that attempts to request a wake lock.
export const requestWakeLock = async cb => {
try {
wakeLock = await navigator.wakeLock.request("screen");
wakeLock.addEventListener("release", () => {
console.log("Wake Lock was released");
});
console.log("Wake Lock is active");
} catch (err) {
console.error(`${err.name}, ${err.message}`);
cb({
tag: "error",
payload: "wakeLock not supported"
});
}
};
Chrome have recently promoted Wake Lock API out of origin trial in version 84 and seems to work well for Chrome on Android PWA.
Demo: https://reillyeon.github.io/scraps/wakelock.html

Chromecast - How to reconnect to the session after page refresh?

After reloading the page, method
cast.framework.CastContext.getInstance()
returns status 'NOT_CONNECTED' and 'NO_SESSION'
My code example:
const castContext = window.cast.framework.CastContext.getInstance();
castContext.setOptions({
receiverApplicationId:
window.chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,
autoJoinPolicy: window.chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED,
resumeSavedSession: true
});
await castContext.requestSession(); // wait for prompt
const castSession = castContext.getCurrentSession();
const mediaInfo = new window.chrome.cast.media.MediaInfo(mediaUrl);
const request = new window.chrome.cast.media.LoadRequest(mediaInfo);
await castSession.loadMedia(request);
window.player = new window.cast.framework.RemotePlayer();
window.playerController = new window.cast.framework.RemotePlayerController(
window.player);
Can you please tell me how to connect to an existing session and receive information about playing media?
I been looking around for answers for a while and your switch of port make me think.
Switching port not a valid solution!
Why does a solution suddenly stop working without any changes to my Chromecast code?
Answer: Chrome got the hiccups. I guess this is either because of several live-refresh or something went wrong during development and it has been cached?!
Solution: I cleared the application storage and deleted my Chrome profile. After a restart of Chrome my solution reconnects with the chromecast as it did before.

HTML 5 Geo Location Prompt in Chrome

Just starting to get into HTML 5 and an testing out geo location...liking it so far. I am hitting a bit of a speed bump though...when I try to get my geo location, chrome automatically blocks the page from getting my location. This does not happen at other sites such as the site below:
http://html5demos.com/geo
The scripts I'm using:
<script type="text/javascript" JavaScript" SRC="geo.js"></script>
<script type="text/javascript" JavaScript" SRC="Utility.js"></script>
<script type="text/javascript" JavaScript" SRC="jquery.js"></script>
<script type="text/javascript" JavaScript" SRC="modernizr.js"></script>
function get_location() {
if (geo_position_js.init()) {
geo_position_js.getCurrentPosition(show_map, handle_error);
}
}
function show_map(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
alert("lat:" + latitude + " long:" + longitude);
}
function handle_error(err) {
alert(err.code);
if (err.code == 1) {
// user said no!
}
}
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(show_map, handle_error);
} else {
error('not supported');
}
I am testing this out from a local directory on my machine, so there isn't really a "domain" like "http://whatever.com/mytestpage.html". Is this why I am not getting prompted? If so, is it possible to force the browswer to request permission to get the user's geo location and is it possible in my scenario?
There's some sort of security restriction in place in Chrome for using geolocation from a file:/// URI, though unfortunately it doesn't seem to record any errors to indicate that. It will work from a local web server. If you have python installed try opening a command prompt in the directory where your test files are and issuing the command:
python -m SimpleHTTPServer
It should start up a web server on port 8000 (might be something else, but it'll tell you in the console what port it's listening on), then browse to http://localhost:8000/mytestpage.html
If you don't have python there are equivalent modules in Ruby, or Visual Web Developer Express comes with a built in local web server.
None of the above helped me.
After a little research I found that as of M50 (April 2016) - Chrome now requires a secure origin (such as HTTPS) for Geolocation.
Deprecated Features on Insecure Origins
The host "localhost" is special b/c its "potentially secure". You may not see errors during development if you are deploying to your development machine.
As already mentioned in the answer by robertc, Chrome blocks certain functionality, like the geo location with local files. An easier alternative to setting up an own web server would be to just start Chrome with the parameter --allow-file-access-from-files. Then you can use the geo location, provided you didn't turn it off in your settings.
The easiest way is to click on the area left to the address bar and change location settings there. It allows to set location options even for file:///
Make sure it's not blocked at your settings
http://www.howtogeek.com/howto/16404/how-to-disable-the-new-geolocation-feature-in-google-chrome/
if you're hosting behind a server, and still facing issues:
try changing localhost to 127.0.0.1 e.g. http://localhost:8080/ to http://127.0.0.1:8080/
The issue I was facing was that I was serving a site using apache tomcat within an eclipse IDE (eclipse luna).
For my sanity check I was using Remy Sharp's demo:
https://github.com/remy/html5demos/blob/eae156ca2e35efbc648c381222fac20d821df494/demos/geo.html
and was getting the error after making minor tweaks to the error function despite hosting the code on the server (was only working on firefox and failing on chrome and safari):
"User denied Geolocation"
I made the following change to get more detailed error message:
function error(msg) {
var s = document.querySelector('#status');
msg = msg.message ? msg.message : msg; //add this line
s.innerHTML = typeof msg == 'string' ? msg : "failed";
s.className = 'fail';
// console.log(arguments);
}
failing on internet explorer behind virtualbox IE10 on http://10.0.2.2:8080 :
"The current location cannot be determined"
For an easy workaround, just copy the HTML file to some cloud share, such as Dropbox, and use the shared link in your browser. Easy.
I too had this problem when i was trying out Gelocation API. I then started IIS express through visual studio and then accessed the page and It worked without any issue in all browsers.
Check Google Chrome setting and permit location access
Change your default location settings.
On your computer, open Chrome.
At the top right, click More Settings.
Under "Privacy and security," click Site settings.
Click Location.
Turn Ask before accessing on or off.
After I changed those settings, Geolocation worked for me.

Websockets Issue, Perhaps Same Origin Policy?

I have a site hosted at localhost:8000. Now, I have a server listening for websocket connections at localhost:8001. I would like my website to connect to this server through the websocket api like
var conn = new WebSocket('ws://localhost:8001');
But I get some errors in Chromium 6.0.472.62 upon calling
conn.send('something');
That looks like: Uncaught Error: INVALID_STATE_ERR: DOM Exception 11.
In Firefox 4 (4.0b8pre), I get the error:
An attempt was made to use an object that is not, or is no longer, usable" code: "11
I thought this was an issue with the handshake not supporting websocket draft76 on the server, but I am using http://github.com/miksago/node-websocket-server/tree/master/lib/ws/ which claims to support draft75 and draft76.
Also, the initial handshake seems to work fine. I can receive a response from the server upon creating the new WebSocket, however, the problems arise on the call to "send" from the client side.
Is this an issue with the same origin policy since my httpserver is on port 8000 and the websocket server is on 8001? If so, how can I work around this?
Perhaps you need to wait for the onopen event to fire?
var conn = new WebSocket('ws://localhost:8001');
conn.onopen = function (e) {
conn.send('something');
}
conn.onmessage = function (e) {
console.log('got something: ' + e.data);
}
Also, it's a good idea to hook the onclose and onerror events too.