Nightmare conditional click (Terminate page session) - javascript

I'm having a session issue after logging in, and the website offers the option to terminate the connection. However, I want to terminate the connection in the loop through the nightmare and then proceed page scraping process, so how do I do this with the nightmare?
I have attached below screenshot and code snippet.
await nightmare
.goto('https://www.exampleorg.com/home')
.type('#UserName', 'abc123')
.type('#Password', 'Welcome#123')
.type('#ConnectionName', 'test')
.click('#btnLogin')
.wait()
.wait('#event-table-listing')
// .wait('')
.evaluate(() => document.querySelector('body').innerHTML)
.end()
.then(response => {
html = response;
success = true;
})
.catch(err => {
console.log('timeOut error');
console.log('err', err);
success = false;
catchTimeOuterror = '.dataTables_info timed out';
});
I've tried with the conditional browsing but it's not working as I expected

Related

socket in nodejs will not close no matter what

So I'm trying to make a script that will connect a bot to a kahoot. However I can only use a certain name one time otherwise I will get a duplicate name error, even after closing all sockets, terminating sockets, removing listeners, etc. Is there something I'm missing?
Edit: added the cleanup on process end that still doesn't work
var Kahoot = require("kahoot.js-latest");
var colors = require('colors');
var bot = new Kahoot;
function cleanup() {
bot.leave();
bot.removeAllListeners();
bot.socket.close();
bot.socket.terminate();
}
bot.join(process.argv[2], "a")
.then(() => {
console.log("Joining...".cyan);
})
.catch((err) => {
console.log(err);
cleanup();
});
[`exit`, `SIGINT`, `SIGUSR1`, `SIGUSR2`, `SIGTERM`].forEach((eventType) => {
process.on(eventType, (code) => {
for (n in bots) {
cleanup();
}
console.log("Exiting Process with code: ".yellow + code);
})
})
After terminating the process and trying to run it again with the same name, I get a duplicate name error even though surely that connection should be destroyed by now
Edit: the error:
{
description: 'Duplicate name',
type: 'loginResponse',
error: 'USER_INPUT'
}

Service worker offline page won't load

This used to work for me but stopped a couple of months ago and I've tinkered my way right out of being able to figure this out anymore. What am I doing wrong here?
Call the service worker template, no problem:
if(navigator.serviceWorker){
window.addEventListener('load',() => {
navigator.serviceWorker
.register('/sw.js')
.then(console.log('[ServiceWorker] Registered Successfully'))
.catch(err => console.log(`[ServiceWorker] Error: ${err}`));
});
} else {
console.log('Service Worker not supported.');
}
Setup a cache version and preloaded the cache, no problem:
const cacheName='2020.10.06-01';
var cacheFiles = ['/offline.html'];
Installed the Services Worker, no problem:
addEventListener('install', e => {
e.waitUntil(
caches.open(cacheName).then(cache => {
return cache.addAll(cacheFiles);
})
);
});
Activated the Services Worker for auto cache rollover, no problem:
addEventListener('activate', e => {
e.waitUntil(
caches.keys().then(keyList => {
return Promise.all(keyList.map(key => {
if(key !== cacheName) {
return caches.delete(key);
}
}));
})
);
});
Fetching from cache or network, no problem:
addEventListener('fetch', e => {
e.respondWith(async function() {
try {
const cache = await caches.open(cacheName);
const cachedResponse = await cache.match(e.request);
const networkResponsePromise = fetch(e.request);
e.waitUntil(async function() {
const networkResponse = await networkResponsePromise;
await cache.put(e.request, networkResponse.clone());
}());
// Returned the cached response if we have one, otherwise return the network response.
return cachedResponse || networkResponsePromise;
} catch (error) {
console.log('Fetch failed; returning offline page instead.', error);
const cache = await caches.open(cacheName);
const cachedResponse = await cache.match('/offline.html');
return cachedResponse;
}
}());
});
But if the page/resource I'm trying to request is not already in the cache AND the network is not available it refuses to display my 'offline.html' page. (Which I know IS in the cache)
Any ideas?
Here's the Fetch code I wrote in the end that works perfectly for me:
self.addEventListener('fetch', (event) => {
event.respondWith((async() => {
const cache = await caches.open(cacheName);
try {
const cachedResponse = await cache.match(event.request);
if(cachedResponse) {
console.log('cachedResponse: ', event.request.url);
return cachedResponse;
}
const fetchResponse = await fetch(event.request);
if(fetchResponse) {
console.log('fetchResponse: ', event.request.url);
await cache.put(event.request, fetchResponse.clone());
return fetchResponse;
}
} catch (error) {
console.log('Fetch failed: ', error);
const cachedResponse = await cache.match('/en/offline.html');
return cachedResponse;
}
})());
});
This does everything I need, in a very specific order. It checks the cache first, if found it's returned. It checks the network next, if found it caches it first then returns it. Or it displays a custom offline page with a big Reload button to encourage visitors to try again when they are back online.
But the most important this to realise is that doing it this way alows me to display a page and all it's resources with or without network access.
UPDATE: In order to deal with changes to CORS security requirements that where implemented in all browsers between March and August of 2020, I had to make one small change to the 'fetch' event.
Changed from:
const fetchResponse = await fetch(event.request);
To:
const fetchResponse = await fetch(event.request, {mode:'no-cors'});
Replace your fetch event code with this one. For every request your fetch event will be invoked and it will check if your request is found in the cache file list then it will serve the file from there otherwise it will make the fetch call to get the file from server.
self.addEventListener("fetch", function (event) {
event.respondWith(
caches.match(event.request)
.then(function (response) {
if (response) {
return response;
}
return fetch(event.request);
})
);
});
Also you don't need a separate "offline.html" file in your cache file list. Instead add your main application html file and your relevant css and js files in that list. That will make your application completely offline in case of no network.

Django + Service Workers: "a redirected response was used for a request whose redirect mode is not follow" error

I've been trying to build a progressive Django Web App with a service worker and django-pwa. Everything seems to work fine, but whenever I load the page, turn on offline mode in Chrome, and reload, I get this error:
"The FetchEvent for "https://haverford.getdibs.app/login/?redirect_to=/dashboard/" resulted in a network error response: a redirected response was used for a request whose redirect mode is not "follow"".
Now I've seen that someone else came into a seemingly similar problem here, but I don't quite understand what's going on in the answer. I think I need to set the redirect mode to "follow" for a request that I make with my fetch, but I'm not sure how to do that.
Here is my service worker:
var staticCacheName = "django-pwa-v" + new Date().getTime();
var filesToCache = [
'/offline',
];
// Cache on install
self.addEventListener("install", event => {
this.skipWaiting();
event.waitUntil(
caches.open(staticCacheName)
.then(cache => {
return cache.addAll(filesToCache);
})
)
});
// Clear cache on activate
self.addEventListener('activate', event => {
event.waitUntil(
caches.keys().then(cacheNames => {
return Promise.all(
cacheNames
.filter(cacheName => (cacheName.startsWith("django-pwa-")))
.filter(cacheName => (cacheName !== staticCacheName))
.map(cacheName => caches.delete(cacheName))
);
})
);
});
// Serve from Cache
self.addEventListener("fetch", event => {
event.respondWith(
caches.match(event.request)
.then(response => {
return response || fetch(event.request);
})
.catch(() => {
return caches.match('offline');
})
)
});
I'm under the impression that i somehow have to make the event.request's redirect mode to 'follow', but when I put a breakpoint in that line and examine the event.request object, its redirect is set to 'manual'. How would I change it?
Any help in my quest to understanding what the issue actually is would be much appreciated.
Thank you.
Thanks a lot, sideshowbarker.
Method 1 in this link helped solve my problem.
I replaced my install event from this:
self.addEventListener("install", event => {
this.skipWaiting();
event.waitUntil(
caches.open(staticCacheName)
.then(cache => {
return cache.addAll(filesToCache);
})
)
});
to this:
self.addEventListener("install", event => {
this.skipWaiting();
event.waitUntil(
caches.open(staticCacheName)
.then(cache => {
return fetch('/offline')
.then(response => cache.put('/offline', new Response(response.body)));
})
)
});
Of course, right now it only works for that one URL endpoint ('/offline'), but it would be similar for multiple fetch requests I suppose.

Firebase response depending on Firestore Query does not work

Depending on whether there is an entry in Cloud Firestore with the correct DocumentId. However, this does not work because my function sends the status 200 before even finishing the query. So how can I get that working?
Here is my code:
access = false;
admin.firebase().collection("tuere").doc(door).collection("eintritt").get().then((snapshot) => {
snapshot.forEach((doc) => {
if(doc.id === uid){
access = true;
console.log("May open door " + uid);
}
});
}).catch((err) => {
console.log(err);
});
res.status(200).send(access);
When I open the Tab in Chrome and let it load "false" appears, but when I wait like 15 Seconds "May open door (uid)" appears in the Logs.
How can I solve this problem and how can i get my function to run faster?
You should send the HTTP response when the promise resolves, so within the then of the query promise: like that:
access = false;
admin.firebase().collection("tuere").doc(door).collection("eintritt").get()
.then((snapshot) => {
snapshot.forEach((doc) => {
if(doc.id === uid){
access = true;
console.log("May open door " + uid);
}
});
res.status(200).send(access);
}).catch((err) => {
console.log(err);
res.status(500).send(err);
});
Also, you should send an HTTP response in case of error, this is why I added res.status(500).send(err); in the catch
I would suggest you look this video from Doug Stevenson: https://www.youtube.com/watch?v=7IkUgCLr5oA
Also there is a point which surprises me: shouln't you use
admin.firestore().collection("tuere").doc(door)....
instead of
admin.firebase().collection("tuere").doc(door)
I have to look in the reference, but I have the feeling that admin.firebase() does not exist.

How to anotate ServiceWorker with flow?

I'm trying to get 100% code coverage with flow but I'm stuck with anotating my ServiceWorker. It is not throwing any errors, but all self.addEventListener(...) are marked as uncovered. For example in:
self.addEventListener("install", (event) => {
console.log("Event: Install");
event.waitUntil(
//Open the cache
caches
.open(cacheName)
.then((cache) => {
//Adding the files to cache
return cache.addAll(filesToCache).then(() => {
console.log("All files are cached.");
return self.skipWaiting(); //To forces the waiting service worker to become the active service worker
});
})
.catch((err) => {
console.log(err);
})
);
});
Even if I do something like let a = self flow will show this line as uncovered.
I tried changing self to this but that didn't help either :(
Does anyone have an idea how to fix this?

Categories

Resources