How to loop through open browser windows after leaving page object - loops

I’m trying to first open multiple browsers, each with one page by re-using a page object.
I then perform some other actions.
How can I then loop through these open browser windows after leaving the current Page object?
I was thinking of having an array of page objects, or pulling some ID for each object and getting back somehow. Thank you
const puppeteer = require('puppeteer');
async function run () {
const url = 'http://www.example.com';
const browser = await puppeteer.launch({ headless: false });
const defaultContext = await browser.defaultBrowserContext();
const browserCount = 10;
for (let i = 0; i < browserCount; i++) {
const newContext = await browser.createIncognitoBrowserContext();
const page = await newContext.newPage();
await page.goto(url);
}
//Perform some other tasks
//Now loop back through the 10 open browser pages.
//Go to the first open browser window, pull data from the page
//Go to the next open browser window, pull data from page
}
run();

As I said in the comment section, you don't store these opened pages anywhere, so you can't really go back to any of them.
The loop should look more like this:
let pages = [];
for (let i = 0; i < browserCount; i++) {
const newContext = await browser.createIncognitoBrowserContext();
pages.push(await newContext.newPage());
pages[i].goto(url);
}
// now pages.length === 10, so you can work with any of these pages
// e.g. clicking on some element on the second page:
pages[1].click('#loginForm');

Related

If user exit app and when open it start with first screen react native?

Issues:
I completed steps till adding the profile information and moved to the next screen which is contact information. I closed the app and opened it again....The app shows that I have created the profile now i need to do the next steps
Expected Result:
If the user leaves the process of profile creation, start over.
so what you can do is :
In async storage, you can save the page name last where the user visited and data was stored and api responded succesfully, (https://react-native-async-storage.github.io/async-storage/docs/usage_
like :
const callApi = (pageName) => {
const result = await api()
//on sucess
if(result.status === 200){
//store page name like this
await AsyncStorage.setItem('#page_name', pageName)
}
}
Then next time when you come back to app, check what page user was on last:
like :
const checkForPageName = async() => {
const value = await AsyncStorage.getItem('#page_name')
if(value !== null) {
if(value === "secondpage"){
navigation.navigate("secondpage");
}
if(value === "thirdpage"){
navigation.navigate("thirdpage");
}
} else{
// this is first time user is coming
navigation.navigate("FirstPage");
}
}
Hope it helps, feel free for doubts

how to turn off buffering in react-player?

when I try to play the next video it does not start and I guess the problem is buffering.
P.S my url is video.m3u8 files
It works fine, but when i change url nothing happens, i would like to know how can i stop current video and load a new one whe, url changes ?
here's my rewind function
const showVideo = async () => {
sessionStorage.setItem("sPlayerLinkId", params.id);
const body = new FormData();
const mac = window.TvipStb.getMainMacAddress();
body.append("link_id", params.id);
body.append("mac", mac);
let response = await fetch(getVideo, {
method: "POST",
body: body,
});
let data = await response.json();
if (data.error) {
openDialog("crush");
return 0;
}
if (_isMounted.current) setVideoLink(data.response.url); };
var goToNext = function () {
playerRef.current.seekTo(0, "seconds");
setVideoLink(null);
if (playerInfo.next_id) {
params.id = playerInfo.next_id;
showVideo();
} else navigate(-1);};
<ReactPlayer
url={videoLink}
playing={isPlaying}
ref={playerRef}
key={params.id}
onProgress={() => {
current();
}}
config={{
file: {
forceHLS: true,
},
}}
/>
I would suggest you build your own player from scratch using just react and a style library.
I had similar issues using react-player and I had to resort to building my own custom player in which I could now ensure that buffering is handled the way I expect it to.
I handled buffering using the progress event as follows
const onProgress = () => {
if (!element.buffered) return;
const bufferedEnd = element.buffered.end(element.buffered.length - 1);
const duration = element.duration;
if (bufferRef && duration > 0) {
bufferRef.current!.style.width = (bufferedEnd / duration) * 100 + "%";
}
};
element.buffered represents a collection of buffered time ranges.
element.buffered.end(element.buffered.length - 1) gets the time at the end of the buffer range. With this value, I was able to compute the current buffer range and update the buffer progress accordingly.
I ended up writing an article that would help others learn to build an easily customizable player from scratch using just React and any style library (in this case charkra UI was used).

Problem with Media toggle in MediaStream APIs

I'm trying to develop a video-conferencing application like GoogleMeet and I'm facing a problem as follows:
Let's say I'm sharing my screen with the others and now I want to turn on my camera. When I turn it on, I have to replace my video.srcObject from DisplayMedia to UserMedia and it works just fine. But when I turn my camera off, my screen should switch back to the screen that was initially shared. For this I tried to save my DisplayMedia object first before switching, but it doesn't work that way and my screen goes blank. for now I'm just creating a new object whenever I switch, It is good if I have to switch back to the camera but when I've to switch back to the screen as mentioned in above example, It requests the user again for which screen to share which is annoying.
Here is the code for my Camera:
const videoRef = useRef();
const userCameraCapture = async cameraIsOn => {
if(cameraIsOn){
if(screenStream)
removeVideoTracks();
let stream = await navigator.mediaDevices.getUserMedia({video:true});
setCameraStream(stream);
videoRef.current.srcObject = stream;
}else{
removeVideoTracks();
setCameraStream(null);
if(screenStream){
videoRef.current.srcObject = await navigator.mediaDevices.getDisplayMedia({video:true});
}else{
videoRef.current.srcObject = null;
}
}
}
and for screen sharing:
const userCameraCapture = async cameraIsOn => {
if(cameraIsOn){
if(screenStream)
removeVideoTracks();
let stream = await navigator.mediaDevices.getUserMedia({video:true});
setCameraStream(stream);
videoRef.current.srcObject = stream;
}else{
removeVideoTracks();
setCameraStream(null);
if(screenStream){
videoRef.current.srcObject = await navigator.mediaDevices.getDisplayMedia({video:true});
}else{
videoRef.current.srcObject = null;
}
}
}
These functions are toggled by a child component and they are working properly other than the problem above.The videoRef is reference to a video tag.

SAS key permissions getting change when using blobserviceclient

I am trying to upload files to blob storage in azure from a react webapp but am having issues with the signature in the authorization header.
This is how the sasToken looks in my code
const sasToken = `sv=2020-08-04&ss=bfqt&srt=sco&sp=rwdlacupx&se=2021-09-22T00:41:33Z&st=2021-09-20T16:41:33Z&spr=https&sig=svP%2FecNOoteE%2**************%3D`;
const containerName = `containername`;
const storageAccountName = "acountname";
This is what it looks like the the GET and PUT requests of getBlobsInContainer and createBlobinContainer run.
sv=2020-08-04&ss=bfqt&srt=sco&sp=ghostery&se=2021-09-22T00:41:33Z&st=2021-09-20T16:41:33Z&spr=https&sig=svP/FecNOoteE/**************=
It's somehow overwriting the permission parameter in the token.
https://accountname.blob.core.windows.net/containername?SAS&comp=list&restype=container&_=1632199288178
The 3 functions I have to deal with it.
// return list of blobs in container to display
const getBlobsInContainer = async (containerClient) => {
const returnedBlobUrls = [];
// get list of blobs in container
// eslint-disable-next-line
for await (const blob of containerClient.listBlobsFlat()) {
// if image is public, just construct URL
returnedBlobUrls.push(
`https://${storageAccountName}.blob.core.windows.net/${containerName}/${blob.name}`
);
}
return returnedBlobUrls;
};
const createBlobInContainer = async (containerClient, file) => {
console.log(`initialising blobclient for ${file.name}`);
// create blobClient for container
const blobClient = containerClient.getBlockBlobClient(file.name);
console.log("blobclient generated");
// set mimetype as determined from browser with file upload control
const options = { blobHTTPHeaders: { blobContentType: file.type } };
// upload file
await blobClient.uploadBrowserData(file, options);
console.log("Adding Metadata");
await blobClient.setMetadata({UserName : 'Reynolds'});
};
const uploadFileToBlob = async (file) => {
if (!file) return [];
// get BlobService = notice `?` is pulled out of sasToken - if created in Azure portal
const blobService = new BlobServiceClient(
`https://${storageAccountName}.blob.core.windows.net?${sasToken}`
);
console.log(`blobservice: https://${storageAccountName}.blob.core.windows.net/?${sasToken}`);
// get Container - full public read access
const containerClient = blobService.getContainerClient(containerName);
// upload file
await createBlobInContainer(containerClient, file);
// // get list of blobs in container
return getBlobsInContainer(containerClient);
};
I'm basically trying to figure out why this is happening and how to prevent/avoid it. The code runs till the console.log(`blobservice: https://${storageAccountName}.blob.core.windows.net/?${sasToken}`); before breaking due to Error 403 from invalid signature.

Variable outside of FB API fetch value returns undefined

I'm trying to loop the URL in FB API so that I can retrieve all the photos without paginating it (for photo searching), but when i try to define the value for "after", it always returns undefined. This is the code:
let next;
for (let ctr=0; ctr<albumcount; ctr++) {
let url = '';
if (ctr>0) {
console.log(ctr, next)
url = `https://graph.facebook.com/v3.2/${val}?fields=photos.limit(100)%7Bimages%2Cname%2Clink%7D&after=${next}&access_token=${access_token}`;
} else {
url = `https://graph.facebook.com/v3.2/${val}?fields=photos.limit(100)%7Bimages%2Cname%2Clink%7D&access_token=${access_token}`;
}
fetch(url)
.then(results => {
return results.json();
}).then(data => {
next = data.photos.paging.cursors.after;
});
}
I've been trying multiple things but "next" always returns undefined. How do I return a value for "next".
Thanks in advance.
fetch/AJAX is asynchronous. So the whole loop will be completely finished BEFORE you even get to the first fetch callback. You can use a recursive function for that, or (even better) async/await:
let result = await fetch(url);
Also, you should not use the album count for the loop - just loop as long as there is a "next" link in the response.

Resources