Workbox cache group is not correct - caching

I'm using workbox-webpack-plugin v5 (the latest) with InjectManifest plugin. The following is my service worker source file:
import { CacheableResponsePlugin } from 'workbox-cacheable-response';
import { clientsClaim, setCacheNameDetails, skipWaiting } from 'workbox-core';
import { ExpirationPlugin } from 'workbox-expiration';
import {
cleanupOutdatedCaches,
createHandlerBoundToURL,
precacheAndRoute,
} from 'workbox-precaching';
import { NavigationRoute, registerRoute, setCatchHandler } from 'workbox-routing';
import { CacheFirst, NetworkOnly, StaleWhileRevalidate } from 'workbox-strategies';
setCacheNameDetails({
precache: 'install-time',
prefix: 'app-precache',
runtime: 'run-time',
suffix: 'v1',
});
cleanupOutdatedCaches();
clientsClaim();
skipWaiting();
precacheAndRoute(self.__WB_MANIFEST);
precacheAndRoute([{ url: '/app-shell.html', revision: 'html-cache-1' }], {
cleanUrls: false,
});
const handler = createHandlerBoundToURL('/app-shell.html');
const navigationRoute = new NavigationRoute(handler);
registerRoute(navigationRoute);
registerRoute(
/.*\.css/,
new CacheFirst({
cacheName: 'css-cache-v1',
})
);
registerRoute(
/^https:\/\/fonts\.(?:googleapis|gstatic)\.com/,
new CacheFirst({
cacheName: 'google-fonts-cache-v1',
plugins: [
new CacheableResponsePlugin({
statuses: [0, 200],
}),
new ExpirationPlugin({
maxAgeSeconds: 60 * 60 * 24 * 365,
maxEntries: 30,
}),
],
})
);
registerRoute(
/.*\.js/,
new StaleWhileRevalidate({
cacheName: 'js-cache-v1',
})
);
setCatchHandler(new NetworkOnly());
I have the following questions/problems:
Cache group is not correct. Everything except google fonts is under workbox-precache-v2 or app-precache-install-time-v1 cache group, not individual cache groups such as css-cache-v1, js-cache-v1. However, 1 in 20 times, it shows correct cache group, and I just can't figure out why.
Google font shows from memory cache. Is it correct? It works fine in offline, but what will happen if the user closes the browser/machine and comes back in offline mode?
Is '/app-shell.html' usage correct? It's an express backend app with * as the wild card for all routes, and React Router handles the routing. Functionally, it's working fine offline. I don't have any app-shell.html page.
Thanks for your help.

Cache group is not correct. Everything except google fonts is under workbox-precache-v2 or app-precache-install-time-v1 cache group, not individual cache groups such as css-cache-v1, js-cache-v1. However, 1 in 20 times, it shows correct cache group, and I just can't figure out why.
It depends on what's in your precache manifest (i.e. what self.__WB_MANIFEST gets replaced with during your webpack build).
For example, let's say you have a file generated by webpack called bundle.js, and that file ends up in your precache manifest. Based on your service worker code, that file will end up in a cached called app-precache-install-time-v1—even though it also matches your runtime route with the cache js-cache-v1.
The reason is because your precache route is registered before you runtime route, so your precaching logic will handle that request rather than your runtime caching logic.
Google font shows from memory cache. Is it correct? It works fine in offline, but what will happen if the user closes the browser/machine and comes back in offline mode?
I believe this means the request is not being handled by the service worker, but you can check the workbox logs in the developer console to verify (and see why not).
Alternatively, you could update your code to use a custom handler that just logs whether it's running like so:
registerRoute(
/^https:\/\/fonts\.(?:googleapis|gstatic)\.com/,
({request}) => {
// Log to make sure this function is being called...
console.log(request.url);
return fetch(request);
}
);
Is '/app-shell.html' usage correct? It's an express backend app with * as the wild card for all routes, and React Router handles the routing. Functionally, it's working fine offline. I don't have any app-shell.html page.
Does your express route respond with a file called app-shell.html? If so, then you'd probably want your precache revision to be a hash of the file itself (rather than revision: 'html-cache-1'). What you have right now should work, but the risk is you'll change the contents of app-shell.html, deploy a new version of your app, but your users will still see the old version because you forgot up update revision: 'html-cache-1'. In general it's best to use revisions generated as part of your build step.

Related

How to test Stripe Google/Apple pay button using Cypress? [duplicate]

I have to call stripe.redirectToCheckout (https://stripe.com/docs/js/checkout/redirect_to_checkout) in js to take a customer to their stripe checkout page.
I want to use cypress to test the checkout process, but it is not able to handle the stripe redirect as the cypress frame is lost when stripe.redirectToCheckout navigates to the page on Stripe's domain.
I also want to test that Stripe redirects us back to the success or error URL.
Is there any way to force cypress to "reattach" to the page once we've navigated to the Stripe checkout
-or-
Is there any way to get the URL for the Stripe checkout page so we can redirect manually or just know that it was at least called with the right parameters.
I know that testing external sites is considered an "anti-pattern" by the people at cypress (https://github.com/cypress-io/cypress/issues/1496). But how can a very standard web process, checkout, be tested (with a very popular and standard payment service, I will add) in that case? I don't buy that this is an "anti-pattern". This is an important step of the end-to-end test, and Stripe specifically gives us a testing sandbox for this kind of thing.
One common way to e2e test application with external dependencies like stripe is to make a simple mock version of it, that is then applied in e2e testing. The mock can also be applied during development, to speed things up.
Would this help?
it(`check stripe redirection`, () => {
cy.get('#payButton').click();
cy.location('host', { timeout: 20 * 1000 }).should('eq', STRIPE_REDIRECT_URL);
// do some payment stuff here
// ...
// after paying return back to local
cy.location({ timeout: 20 * 1000 }).should((location) => {
expect(location.host).to.eq('localhost:8080')
expect(location.pathname).to.eq('/')
})
})
I've used this method to test keyCloak login. This is the actual code that worked.
describe('authentication', () => {
beforeEach(() => cy.kcLogout());
it('should login with correct credentials', () => {
cy.visit('/');
cy.location('host', { timeout: 20 * 1000 }).should('eq', 'keycloak.dev.mysite.com:8443');
// This happens on https://keycloak.dev.mysite.com:8443/auth/dealm/...
cy.fixture('userCredentials').then((user) => {
cy.get('#username').type(user.email);
cy.get('#password').type(user.password);
cy.get('#kc-login').click();
cy.location({ timeout: 20 * 1000 }).should((location) => {
expect(location.host).to.eq('localhost:8080')
expect(location.pathname).to.eq('/')
})
})
});
I'm giving it a try to use stripe elements instead since it does not redirect and gives me much more control over it.

How to allow clients to hook into preconfigured hooks in application

I have a pretty standard application with a frontend, a backend and some options in the frontend for modifying data. My backend fires events when data is modified (eg. record created, record updated, user logged in, etc.).
Now what I want to do is for my customers to be able to code their own functions and "hook" them into these events.
So far the approaches I have thought of are:
Allowing users in the frontend to write some code in a codeeditor like codemirror, but this whole storing code and executing it with some eval() seems kind of risky and unstable.
My second approach is illustrated below (to the best of my ability at least). The point is that the CRUD API calls a different "hook" web service that has these (recordUpdated, recordCreated, userLoggedIn,...) hook methods exposed. Then the client library needs to extend some predefined interfaces for the different hooks I expose. This still seems doable, but my issue is I can't figure out how my customers would deploy their library into the running "hook" service.
So it's kind of like webhooks, except I already know the exact hooks to be created which I figured could allow for an easier setup than customers having to create their own web services from scratch, but instead just create a library that is then deployed into an existing API (or something like that...). Preferably the infrastructure details should be hidden from the customers so they can focus solely on making business logic inside their custom hooks.
It's kind of hard to explain, but hopefully someone will get and can tell me if I'm on the right track or if there is a more standard way of doing hooks like these?
Currently the entire backend is written in C# but that is not a requirement.
I'll just draft out the main framework, then wait for your feedback to fill in anything unclear.
Disclaimer: I don't really have expertise with security and sandboxing. I just know it's an important thing, but really, it's beyond me. You go figure it out 😂
Suppose we're now in a safe sandbox where all malicious behaviors are magically taken care, let's write some Node.js code for that "hook engine".
How users deploy their plugin code.
Let's assume we use file-base deployment. The interface you need to implement is a PluginRegistry.
class PluginRegistry {
constructor() {
/**
The plugin registry holds records of plugin info:
type IPluginInfo = {
userId: string,
hash: string,
filePath: string,
module: null | object,
}
*/
this.records = new Map()
}
register(userId, info) {
this.records.set(userId, info)
}
query(userId) {
return this.records.get(userId)
}
}
// plugin registry should be a singleton in your app.
const pluginRegistrySingleton = new PluginRegistry()
// app opens a http endpoint
// that accepts plugin registration
// this is how you receive user provided code
server.listen(port, (req, res) => {
if (isPluginRegistration(req)) {
let { userId, fileBytes, hash } = processRequest(req)
let filePath = pluginDir + '/' + hash + '.js'
let pluginInfo = {
userId,
// you should use some kind of hash
// to uniquely identify plugin
hash,
filePath,
// "module" field is left empty
// it will be lazy-loaded when
// plugin code is actually needed
module: null,
}
let existingPluginInfo = pluginRegistrySingleton.query(userId)
if (existingPluginInfo.hash === hash) {
// already exist, skip
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('ok');
} else {
// plugin code written down somewhere
fs.writeFile(filePath, fileBytes, (err) => {
pluginRegistrySingleton.register(userId, pluginInfo)
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('ok');
})
}
}
})
From the perspective of hook engine, it simply opens a HTTP endpoint to accept plugin registration, agnostic to the source.
Whether it's from CI/CD pipeline, or plain web interface upload, it doesn't matter. If you have CI/CD setup for your user, it is just a dedicated build machine that runs bash scripts isn't it? So just fire a curl call to this endpoint to upload whatever you need. Same applies to web interface.
How we would execute plugin code
User plugin code is just normal Node.js module code. You might instruct them to expose certain API and conform to your protocol.
class HookEngine {
constructor(pluginRegistry) {
// dependency injection
this.pluginRegistry = pluginRegistry
}
// hook
oncreate(payload) {
// hook call payload should identify the user
const pluginInfo = this.pluginRegistry.query(payload.user.id)
// lazy-load the plugin module when needed
if (pluginInfo && !pluginInfo.module) {
pluginInfo.module = require(pluginInfo.filePath)
}
// user plugin module is just normal Node.js module
// you load it with `require`, and you call what ever function you need.
pluginInfo.module.oncreate(payload)
}
}

WordPress admin-ajax.php 400 error generated by Event Tickets plugin ... database related?

I have a WordPress website for a client that uses a custom theme and a number of plugins in combination to create an events calendar where logged in users can purchase tickets for paid events and register for free RSVP-required events. To accomplish this, I am using the following six plugins in combination:
The Events Calendar
Events Calendar Pro
Event Tickets
Event Tickets Plus
WooCommerce
WooCommerce Stripe Gateway
The website was established in 2015. In the last 4 years, those plugins have seen extensive updates, and as a result, at a certain point the custom site I built around those plugins started experiencing deprecation issues, and attempts to upgrade caused performance failure. After consulting with support, it became necessary to pull a duplicate copy of the site onto a development server so that I could do the work to upgrade the install so all the latest versions of all of these plugins can be running and working properly.
Everything was going well with the upgrade work until I noticed that one of the plugins seems to be generating the following error in the console in Chrome:
POST https://pcapolar.codewordserver.com/wp-admin/admin-ajax.php 400 (Bad Request)
send # jquery.js?ver=1.12.4-wp:4
ajax # jquery.js?ver=1.12.4-wp:4
n.<computed> # jquery.js?ver=1.12.4-wp:4
r.length.e.checkAvailability # frontend-ticket-form.min.js?ver=4.11.1:1
r.length.e.init # frontend-ticket-form.min.js?ver=4.11.1:1
(anonymous) # frontend-ticket-form.min.js?ver=4.11.1:1
(anonymous) # frontend-ticket-form.min.js?ver=4.11.1:1
Loading the same page in Edge generated the following console error:
HTTP400: BAD REQUEST - The request could not be processed by the server due to invalid syntax
(XHR)POST - https://pcapolar.codewordserver.com/wp-admin/admin-ajax.php
The error occurs only under very specific circumstances -- when a single event page displays the frontend form for a paid ticket. The error doesn't occur when the front end paid ticket form is not output, for example when there is a registered RSVP form with no payment component, when there is no ticket component to the event, or when a user who is not an active member views an affected page such that all information about details of the event and buying tickets is excluded from the output via theme template files. Despite the console error generated, it appears that ajax works fine and all of the functionality works exactly as expected. If you weren't looking at the console, you'd never know there was a problem.
In order to rule out an issue with my custom theme or a conflict with another plugin, I activated the default Twenty Twenty theme and deactivated all other plugins except the 6 I listed that are required to use ticketed event process. The error remained present under these circumstances
After going back and forth with Modern Tribe (the plugin developers) support desk, they report the error cannot be replicated. So I tried myself to install a clean copy of WordPress with a new database, then install only those 6 plugins while running the default Twenty Twenty theme. I did this on the same server under the same cPanel account as the dev site with the error, just at different subdomains. On the clean install, the error was NOT present. But when I then pointed the clean WordPress install to a duplicate copy of the database I'm using for the dev site I'm working on, the error shows up again. From that, I can only conclude there is something going on in my database that is making this error happen, but Modern Tribe support are telling me that since the error can't be reproduced by them, there isn't anything they can do to help.
Starting over with a clean install for this site isn't really an option, there is so much data collected over the last 4 years from ticket purchase and membership transactions that we really can't lose. I need to find the faulty data and clean it, but I feel out of my depth here. Any help or suggestions on how to resolve this are welcome.
Edited to add:
I found this code in the javascript file references by the error message in the console. Am I looking in the right place?
/**
* Check tickets availability.
*
* #since 4.9
*
* #return void
*/
obj.checkAvailability = function() {
// We're checking availability for all the tickets at once.
var params = {
action : 'ticket_availability_check',
tickets : obj.getTickets(),
};
$.post(
TribeTicketOptions.ajaxurl,
params,
function( response ) {
var success = response.success;
// Bail if we don't get a successful response.
if ( ! success ) {
return;
}
// Get the tickets response with availability.
var tickets = response.data.tickets;
// Make DOM updates.
obj.updateAvailability( tickets );
}
);
// Repeat every 60 (filterable via tribe_tickets_availability_check_interval ) seconds
if ( 0 < TribeTicketOptions.availability_check_interval ) {
setTimeout( obj.checkAvailability, TribeTicketOptions.availability_check_interval );
}
}
Edited to add:
Then I ran a string search for ticket_availability and found the following. It looks like it might be related, but I'm a bit over my head in interpreting. Am I on the right track yet?
public function ticket_availability( $tickets = array() ) {
$response = array( 'html' => '' );
$tickets = tribe_get_request_var( 'tickets', array() );
// Bail if we receive no tickets
if ( empty( $tickets ) ) {
wp_send_json_error( $response );
}
/** #var Tribe__Tickets__Tickets_Handler $tickets_handler */
$tickets_handler = tribe( 'tickets.handler' );
/** #var Tribe__Tickets__Editor__Template $tickets_editor */
$tickets_editor = tribe( 'tickets.editor.template' );
// Parse the tickets and create the array for the response
foreach ( $tickets as $ticket_id ) {
$ticket = Tribe__Tickets__Tickets::load_ticket_object( $ticket_id );
if (
! $ticket instanceof Tribe__Tickets__Ticket_Object
|| empty( $ticket->ID )
) {
continue;
}
$available = $tickets_handler->get_ticket_max_purchase( $ticket->ID );
$response['tickets'][ $ticket_id ]['available'] = $available;
// If there are no more available we will send the template part HTML to update the DOM
if ( 0 === $available ) {
$response['tickets'][ $ticket_id ]['unavailable_html'] = $tickets_editor->template( 'blocks/tickets/quantity-unavailable', $ticket, false );
}
}
wp_send_json_success( $response );
}
The weird thing is that this function is filed to a folder called Blocks, which implied it works with Gutenberg, which I have disabled via the Classic Editor plugin.
StackOverflow powers that be, forgive me but this was too much to fit in a comment.
I apologize, but this is more of a debug process than a strict answer.
The admin-ajax.php file only has 3 scenarios to return a 400 error.
If the user is logged in, and the ajax function hasn't been added to the wp_ajax_{function_name} action. (line #164)
The user is NOT logged in, and the ajax function hasn't been added to the wp_ajax_nopriv_{function_name} action. (line #179)
No action was sent in the request. (line #32)
You'll need to figure out which of these is causing your error. If you're not sure how to do this, an easy way is to temporarily edit your admin-ajax.php file. Before you see this:
// Require an action parameter
if ( empty( $_REQUEST['action'] ) ) {
wp_die( '0', 400 );
}
Add in the following (again, before the above lines)
ob_start();
print( '<pre>'. print_r($_REQUEST, true) .'</pre>' );
wp_mail( 'your-email#address.com', 'Debug Results', ob_get_clean() );
This will email you (semi-nicely) formatted dump of the $_REQUEST. If there's no action, you'll know that for some reason the "front end form for a paid ticket" function isn't being added, and Modern Tribe could probably help you out with that.
If the action is set, you can add a similar line down below at line 164 or 179 and repeat the above, but with print( '<pre>'. print_r($action, true) .'</pre>' ); instead. If either of these get emailed to you when you submit the form, you'll know which ajax hook isn't being added, and again Modern Tribe could probably help you from there.
Also note, that modifying core WP files is generally bad practice and you should revert these changes when you're done debugging. (There's ways to hook into file instead, but for ease/speed of diagnostics, go ahead and temporarily edit it, as these aren't permanent changes, and it's on a development site, so you shouldn't have to worry)
Beyond the above, you'll probably need to hire a developer look at it, there's not much more that someone on Stack Overflow can do without having direct access to your database and files.
I am having the same problem and I think the problem is Tribe__Editor::should_load_blocks when the classic editor plugin is active.
To bypass this error I add this code to my theme functions.php file
add_action( 'xxx', tribe_callback( 'tickets.editor.blocks.tickets', 'register' ) );
do_action( 'xxx' );
I hope this works for you.
The advice I received from the plugin developers after a great deal of back and forth was to add the following to my theme's functions.php file:
add_filter( 'tribe_tickets_availability_check_interval', function( $interval) {
return 0;
} );
This resolves the console issue, does not generate additional errors, and does not interfere with any expected functionality in all tests performed thus far.
Wanted to update everyone that with the release of Event Tickets 4.11.4 and Event Tickets Plus 4.11.3, this issue has been completely resolved on the plugin side. So apparently this was not just an issue with my site only. Thank you to everyone who contributed.

Tips on solving 'DevTools was disconnected from the page' and Electron Helper dies

I've a problem with Electron where the app goes blank. i.e. It becomes a white screen. If I open the dev tools it displays the following message.
In ActivityMonitor I can see the number of Electron Helper processes drops from 3 to 2 when this happens. Plus it seems I'm not the only person to come across it. e.g.
Facing "Devtools was disconnected from the page. Once page is reloaded, Devtools will automatically reconnect."
Electron dying without any information, what now?
But I've yet to find an answer that helps. In scenarios where Electron crashes are there any good approaches to identifying the problem?
For context I'm loading an sdk into Electron. Originally I was using browserify to package it which worked fine. But I want to move to the SDKs npm release. This version seems to have introduced the problem (though the code should be the same).
A good bit of time has passed since I originally posted this question. I'll answer it myself in case my mistake can assist anyone.
I never got a "solution" to the original problem. At a much later date I switched across to the npm release of the sdk and it worked.
But before that time I'd hit this issue again. Luckily, by then, I'd added a logger that also wrote console to file. With it I noticed that a JavaScript syntax error caused the crash. e.g. Missing closing bracket, etc.
I suspect that's what caused my original problem. But the Chrome dev tools do the worst thing by blanking the console rather than preserve it when the tools crash.
Code I used to setup a logger
/*global window */
const winston = require('winston');
const prettyMs = require('pretty-ms');
/**
* Proxy the standard 'console' object and redirect it toward a logger.
*/
class Logger {
constructor() {
// Retain a reference to the original console
this.originalConsole = window.console;
this.timers = new Map([]);
// Configure a logger
this.logger = winston.createLogger({
level: 'info',
format: winston.format.combine(
winston.format.timestamp(),
winston.format.printf(({ level, message, timestamp }) => {
return `${timestamp} ${level}: ${message}`;
})
),
transports: [
new winston.transports.File(
{
filename: `${require('electron').remote.app.getPath('userData')}/logs/downloader.log`, // Note: require('electron').remote is undefined when I include it in the normal imports
handleExceptions: true, // Log unhandled exceptions
maxsize: 1048576, // 10 MB
maxFiles: 10
}
)
]
});
const _this = this;
// Switch out the console with a proxied version
window.console = new Proxy(this.originalConsole, {
// Override the console functions
get(target, property) {
// Leverage the identical logger functions
if (['debug', 'info', 'warn', 'error'].includes(property)) return (...parameters) => {
_this.logger[property](parameters);
// Simple approach to logging to console. Initially considered
// using a custom logger. But this is much easier to implement.
// Downside is that the format differs but I can live with that
_this.originalConsole[property](...parameters);
}
// The log function differs in logger so map it to info
if ('log' === property) return (...parameters) => {
_this.logger.info(parameters);
_this.originalConsole.info(...parameters);
}
// Re-implement the time and timeEnd functions
if ('time' === property) return (label) => _this.timers.set(label, window.performance.now());
if ('timeEnd' === property) return (label) => {
const now = window.performance.now();
if (!_this.timers.has(label)) {
_this.logger.warn(`console.timeEnd('${label}') called without preceding console.time('${label}')! Or console.timeEnd('${label}') has been called more than once.`)
}
const timeTaken = prettyMs(now - _this.timers.get(label));
_this.timers.delete(label);
const message = `${label} ${timeTaken}`;
_this.logger.info(message);
_this.originalConsole.info(message);
}
// Any non-overriden functions are passed to console
return target[property];
}
});
}
}
/**
* Calling this function switches the window.console for a proxied version.
* The proxy allows us to redirect the call to a logger.
*/
function switchConsoleToLogger() { new Logger(); } // eslint-disable-line no-unused-vars
Then in index.html I load this script first
<script src="js/logger.js"></script>
<script>switchConsoleToLogger()</script>
I had installed Google Chrome version 79.0.3945.130 (64 bit). My app was going to crash every time when I was in debug mode. I try all the solutions I found on the web but no one was useful. I downgrade to all the previous version:
78.x Crashed
77.x Crashed
75.x Not Crashed
I had to re-install the version 75.0.3770.80 (64 bit). Problem has been solved. It can be a new versions of Chrome problem. I sent feedback to Chrome assistence.
My problem was that I was not loading a page such as index.html. Once I loaded problem went away.
parentWindow = new BrowserWindow({
title: 'parent'
});
parentWindow.loadURL(`file://${__dirname}/index.html`);
parentWindow.webContents.openDevTools();
The trick to debugging a crash like this, is to enable logging, which is apparently disabled by default. This is done by setting the environment variable ELECTRON_ENABLE_LOGGING=1, as mentioned in this GitHub issue.
With that enabled, you should see something along the lines of this in the console:
You can download Google Chrome Canary. I was facing this problem on Google Chrome where DevTools was crashing every time on the same spot. On Chrome Canary the debugger doesn't crash.
I also faced the exact same problem
I was trying to require sqlite3 module from renderer side
which was causing a problem but once i removed the request it was working just fine
const {app , BrowserWindow , ipcMain, ipcRenderer } = require('electron')
const { event } = require('jquery')
const sqlite3 = require('sqlite3').verbose(); // <<== problem
I think the best way to solve this (if your code is really really small) just try to remove functions and run it over and over again eventually you can narrow it down to the core problem
It is a really tedious , dumb and not a smart way of doing it , but hey it worked
I encountered this issue, and couldn't figure out why the the DevTool was constantly disconnecting. So on a whim I launched Firefox Developer edition and identified the cause as an undefined variable with a string length property.
if ( args.length > 1 ) {
$( this ).find( "option" ).each(function () {
$( $( this ).attr( "s-group" ) ).hide();
});
$( args ).show();
}
TL;DR Firefox Developer edition can identify these kinds of problems when Chrome's DevTool fails.
After reading the comments above it is clear to me that there is a problem at least in Chrome that consists of not showing any indication of what the fault comes from. In Firefox, the program works but with a long delay.
But, as Shane Gannon said, the origin of the problem is certainly not in a browser but it is in the code: in my case, I had opened a while loop without adding the corresponding incremental, which made the loop infinite. As in the example below:
var a = 0;
while (a < 10) {
...
a ++ // this is the part I was missing;
}
Once this was corrected, the problem disappeared.
I found that upgrading to
react 17.0.2
react-dom 17.0.2
react-scripts 4.0.3
but also as react-scripts start is being used to run electron maybe its just react scripts that needs updating.
Well I nearly went crazy but with electron the main problem I realized I commented out the code to fetch (index.html)
// and load the index.html of the app.
mainWindow.loadFile('index.html');
check this side and make sure you have included it. without this the page will go black or wont load. so check your index.js to see if there's something to load your index.html file :) feel free to mail : profnird#gmail.com if you need additional help
Downgrade from Electron 11 to Electron 8.2 worked for me in Angular 11 - Electron - Typeorm -sqlite3 app.
It is not a solution as such, but it is an assumption of why the problem.
In the angular 'ngOnInit' lifecycle I put too many 'for' and 'while' loops, one inside the other, after cleaning the code and making it more compact, the problem disappeared, I think maybe because it didn't finish the processes within a time limit I hope someone finds this comment helpful. :)
I have stumbled upon the similar problem, My approach is comment out some line that I just added to see if it works. And if that is the case, those problem is at those lines of code.
for(var i = 0;i<objLen; i+3 ){
input_data.push(jsonObj[i].reading2);
input_label.push(jsonObj[i].dateTime);
}
The console works fine after i change the code to like this.
for(var i = 0;i<objLen; i=i+space ){
input_data.push(jsonObj[i].reading2);
input_label.push(jsonObj[i].dateTime);
}
Open your google dev console (Ctrl + shift + i). Then press (fn + F1) or just F1, then scroll down and click on the Restore defaults and reload.

Django Channels - Handshaking & Connect, but websocket.connect function is not executed

I'm working on a django project with channels involved in different apps. The first app (receiving data from a sensor) has it's own consumer and routing, as well as the second one (updates a list of logged in users).
Within the first app everything works fine.
In the second app the handshake is completed and the connection is established, but the function, that is linked to websocket.receive is not executed.
from channels.routing import route, route_class
from channels.staticfiles import StaticFilesConsumer
from users.consumer import ws_connect, ws_disconnect
channel_routing = [
route('websocket.connect', ws_connect, path=r'^/users/lobby/'),
...
]
and the ws_connect
import json
from channels import Group
from channels.handler import AsgiHandler
from channels.auth import channel_session_user,
channel_session_user_from_http, channel_session
#channel_session_user_from_http
def ws_connect(message):
print('test')
The print('test') of ws_connect is never executed. Additionally it even doesn't matter what url ending I'm using in javascript.
var ws = new WebSocket('ws://127.0.0.1:8000/users/lobby/');
ws.onopen = function() {
console.log('connect');
ws.send('connect');
}
The ws of the javascript will connect with .../users/lobby/ or .../lobby/ of .../users/.
Thanks for any hints on this!
Since i apparently need 50 reputation to make a comment i'm just gonna make an answer instead even tho i am not sure this is the solution for you.
I had the same exact problem when copying parts of the the github multichat project made by the guy whom made channels.
My issue was apparently that i hade miss spelled the routing with a slight misstake and therefor it didn't call the correct function i had setup for that routing.
So my advice is that you trippel check the routing everywhere to see if you've messed up. I personally only checked my APP routing when error checking but it was in my project folder i had messed upp my routing.
Another thing that might be cauzing this issue is that you only have a routing in your app, but not in the main folder. In that case you need to include the other app routing with the path you want for it just like a view:
from channels import include
channel_routing = [
include("crypto_chat.routing.websocket_routing", path=r"^/chat/stream/$"),
include("crypto_chat.routing.chat_routing"),
]
App routing:
from channels import route
from .consumers import ws_connect, ws_receive, ws_disconnect, user_offline, user_online, chat_send
websocket_routing = [
route("websocket.connect", ws_connect),
route("websocket.receive", ws_receive),
route("websocket.disconnect", ws_disconnect),
]
chat_routing = [
route("chat.receive", chat_send, command="^send$"),
route("chat.receive", user_online, command="^online$"),
route("chat.receive",user_offline, command="^offline$"),
]
If that doesnt help then i suggest you head over to the github channel page for examples and compare the two. Keep in mind tho that the project is probably made from an erlier version of channels (and maybe django aswell).
https://github.com/andrewgodwin/channels-examples
Hope it helps and as i said i would have made a comment but i can't since of my rep apparently...

Resources