Dynamically attach EventListner to link using JavaScript - javascript

The following code in injected to a wordpress page through functions.php.
I am using SweetAlert2 to launch a popup window that displays consent for TOS.
I am trying to dynamically attach an eventListner to the link launching that popup window.When page is first loaded, monthly in initialized (button is active), but once the oneTime button is clicked, I wish to re-attach the eventListener to the link on that form (show_iframe_2).
Somehow the code behaves strange, at first round it doesn't launch the popup on the oneTime button, but after clicking the link and going back and forth between the 2 forms, it will...
Any ideas how to achieve the task?
window.onload = function () {
const oneTime = document.getElementById("show_iframe_2");
const monthly = document.getElementById("show_iframe_1");
// these are on monthly form elements
let popLink = document.getElementById("privacyLink");
let consentCheckBox = document.getElementById("field_68823bb");
updatePopLink(popLink, consentCheckBox);
async function updatePopLink(link, checkBox) {
if (popLink) {
popLink.removeEventListener("click", launchPopUp);
}
popLink = link;
consentCheckBox = checkBox;
await popLink.addEventListener("click", launchPopUp);
}
function launchPopUp() {
fetch("https://privacy-and-tos-page/")
.then((response) => response.text())
.then((text) => {
// Parse the response text as an HTML document
let parser = new DOMParser();
let doc = parser.parseFromString(text, "text/html");
// Select the element by its id
let element = doc.getElementById("main");
// Get the innerHTML of the selected element
let html = element.innerHTML;
Swal.fire({
title: "",
html: html,
showCancelButton: true,
confirmButtonText: "Confirm",
cancelButtonText: "Cancel",
confirmButtonColor: "#3085d6",
width: 1200,
}).then((result) => {
if (result.value) {
consentCheckBox.checked = true;
} else if (result.dismiss === Swal.DismissReason.cancel) {
consentCheckBox.checked = false;
}
});
});
}
oneTime.addEventListener("click", function (event) {
popLink = document.getElementById("privacyLink");
consentCheckBox = document.getElementById("field_6a9f758");
updatePopLink(popLink, consentCheckBox);
});
monthly.addEventListener("click", function (event) {
popLink = document.getElementById("linkId");
consentCheckBox = document.getElementById("field_68823bb");
updatePopLink(popLink, consentCheckBox);
});
};

As I couldn't find a solution, I simply did the following:
window.onload = (event) => {
let popLinkMonthly = document.getElementById("privacyLink");
let consetCkBoxMonthly = document.getElementById("field_68823bb");
let popLinkOneTime = document.getElementById("linkId");
let consetCkBoxOneTime = document.getElementById("field_68823bb");
popLinkMonthly.addEventListener('click', function(){
fetch("https://some-url/")
.then(response => response.text())
.then(text => {
let parser = new DOMParser();
let doc = parser.parseFromString(text, "text/html");
let element = doc.getElementById("main");
let html = element.innerHTML;
Swal.fire({
title: '',
html: html,
showCancelButton: true,
confirmButtonText: 'Confirm',
cancelButtonText: 'Cancel',
confirmButtonColor: '#3085d6',
width: 1200,
}).then((result) => {
if (result.value) {
consetCkBoxMonthly.checked = true;
} else if (result.dismiss === Swal.DismissReason.cancel) {
consetCkBoxMonthly.checked = false;
}
});
})
});
popLinkOneTime.addEventListener('click', function(){
fetch("https://some-url/")
.then(response => response.text())
.then(text => {
let parser = new DOMParser();
let doc = parser.parseFromString(text, "text/html");
let element = doc.getElementById("main");
let html = element.innerHTML;
Swal.fire({
title: '',
html: html,
showCancelButton: true,
confirmButtonText: 'Confirm',
cancelButtonText: 'Cancel',
confirmButtonColor: '#3085d6',
width: 1200,
}).then((result) => {
if (result.value) {
consetCkBoxOneTime.checked = true;
} else if (result.dismiss === Swal.DismissReason.cancel) {
consetCkBoxOneTime.checked = false;
}
});
})
});
}

Related

how to send whatsapp messages multiple times in whatsappweb

able to send 50 messages in 2.5 sec
i tried again it worked
so this is update code if you find any errores feel free to update me
let messageYouWantToSend = `Good Morning`;
let howManyTime =50;
function resolveAfter2Seconds(message) {
return new Promise(resolve => {
const mk1 = document.querySelector('#main')
const textmk1 = mk1.querySelector('div[contenteditable="true"]')
if (!textmk1) {
throw new Error('There is no opened conversation')
}
textmk1.focus()
document.execCommand('insertText', false, message)
textmk1.dispatchEvent(new Event('change', {
bubbles: true
}))
setTimeout(() => {
(mk1.querySelector('[data-testid="send"]') || mk1.querySelector('[data-icon="send"]')).click()
resolve('sent');
}, 50);
});
}
async function asyncCall(messageUwantToSend2) {
for (let i = 0; i < howManyTime; i++) {
const result = await resolveAfter2Seconds(messageUwantToSend2);
console.log(`${result}==>${i+1}`);
}
}
asyncCall(messageYouWantToSend);

How can I toggle the button text based on HTTP status?

Onclick, I'd like to toggle the button text based on the HTTP status. If the status is 200, then forgotPasswordBtnTxt should change to Sent!, else forgotPasswordBtnTxt should change to Something went wrong!.
I know hooks are async but for some reason everything I've tried has failed. What am I doing wrong?
const [forgotPasswordBtnFlag, setForgotPasswordBtnFlag] = useState(false);
const [forgotPasswordBtnTxt, setForgotPasswordBtnTxt] = useState("Send Forgot Password Link");
const [forgotPasswordStatus, setForgotPasswordStatus] = useState(null);
const forgotPassWordClicked = () => {
setForgotPasswordBtnFlag(true);
setForgotPasswordBtnTxt(forgotPasswordStatus === 200 ? "Sent!" : "Something went wrong!");
};
const handleForgotPassword = (e) => {
e.preventDefault();
let dataForgotPassword = {
'email': forgotPasswordEmail
};
axios.post('http://127.0.0.1:8000/api/forgot-password', dataForgotPassword)
.then(resp => {
let okStatus = resp.status;
setForgotPasswordStatus(okStatus);
}).catch(error => {
let failedStatus = error.response.status;
setForgotPasswordStatus(failedStatus);
});
};
<button type="submit" className={`${!forgotPasswordBtnFlag ? 'btn' : 'forgotPasswordTextSuccess'} sendPasswordResetLinkBtn`} onClick={forgotPassWordClicked}>
{forgotPasswordBtnTxt}
</button>

How to TypeError for Electron App Constructor

Im kind of new to JavaScript and I can't find the issue of the error which im receiving with "document.getElementById("login").innerHTML = "Success!" as I receive a TypeError stating "document.getElementById" is not a function. I want it to read the HTML page input of the password being entered from 'index.html'. The current script is the Electron App Constructor.
var document = ('index.html')
let win;
app.on('ready', () => {
let main = null
let loading = new BrowserWindow({width:400, height:300, frame:false, icon: __dirname + '/assets/Icon.png'})
loading.once('show', () => {
main = new BrowserWindow({width:1800, height:800, minWidth:1600, minHeight:600, webPreferences: {
nodeIntegration: true
}, frame: false, icon: __dirname + '/assets/Icon.png', show: false })
main.webContents.once('dom-ready', () => {
loading.show();
password = document.getElementById("license").value;
if(password == '12345'){
document.getElementById("login").innerHTML = "Success!"
main.show();
} else{
document.getElementById("login").innerHTML = "Wrong password!";
app.quit();
}
})

How to pass a stream from page to page while the user navigates? Chrome extension Manifest V3

I'm developing a manifest v3 Google Chrome extension that aims to take screenshots and record user browsing.
Problem: When I navigate from one page to another while screen sharing the stream is lost.
Question 1: how to pass the stream between navigation pages?
Question 2: how to store the stream so that when loading the next page the stream is maintained?
Note:
In the service worker I use chrome.desktopCapture.chooseDesktopMedia to bring up the screen sharing window, with this I get the stream id which is then sent to the content script found on the page, where I use navigator.mediaDevices.getUserMedia to get the stream which I then place inside a video element. This video object allows me to take screenshots with canvas.
Viewing some extensions with manifest v2 use the background pages to store the video object and the scripts that create the stream. But now with the service worker in manifest v3, how could I do it?
My code:
Service worker:
chrome.runtime.onConnect.addListener(function (port) {
port.onMessage.addListener(function (msg) {
if (msg.type === 'SS_UI_REQUEST') {
requestScreenSharing(port, msg)
}
if (msg.type === 'SS_UI_TAKESCREENSHOT') {
console.log(msg.top);
StartCountDown(port, msg);
}
});
});
// const sources = ['screen', 'window', 'tab', 'audio'];
async function requestScreenSharing(port, msg) {
const sources = ['screen'];
const tab = port.sender.tab;
chrome.desktopCapture.chooseDesktopMedia(
sources,
port.sender.tab,
streamId => {
if (streamId) {
msg.type = 'SS_DIALOG_SUCCESS';
msg.streamId = streamId;
msg.text = "sharing";
} else {
msg.type = 'SS_DIALOG_CANCEL';
msg.text = "cancel";
}
var tab = getTabId();
tab.then((value) => {
const respuesta = chrome.tabs.connect(value.id, {
name: "respuesta",
});
respuesta.postMessage(msg);
});
}
);
}
let seconds = 3;
let id;
async function StartCountDown(port, msg) {
const css1 = 'body::after{ display: flex; height: 100vh;justify-content: center;align-items: center; background:rgb(76,76,76); opacity: 0.7; content: "Capturando pantalla.. 3"; color:white;font-size: 50px;font-weight: 500; width:100%; position: absolute;top:'+msg.top+'px;left: 0; z-index: 2040;}'
const css2 = 'body::after{ content: "Capturando pantalla.. 2";}'
const css3 = 'body::after{ content: "Capturando pantalla.. 1";}'
myIntervalId = setInterval(function () {
IntervalId = myIntervalId;
if (seconds > 0) {
chrome.action.setBadgeBackgroundColor({
color: [255, 0, 0, 255]
});
chrome.action.setBadgeText({
text: seconds.toString()
});
if (seconds == 3) {
var csstab = getTabId();
csstab.then((value) => {
chrome.scripting.insertCSS({
target: {
tabId: value.id
},
css: css1,
});
});
}
if (seconds == 2) {
var csstab = getTabId();
csstab.then((value) => {
chrome.scripting.insertCSS({
target: {
tabId: value.id
},
css: css2,
});
});
}
if (seconds == 1) {
var csstab = getTabId();
csstab.then((value) => {
chrome.scripting.insertCSS({
target: {
tabId: value.id
},
css: css3,
});
});
}
seconds--;
} else {
chrome.action.setBadgeText({
'text': ''
});
seconds = 3;
clearInterval(IntervalId);
msg.type = 'SS_UI_TAKESCREENSHOT_SUCCESS';
msg.text = "takingScreenShot";
var tab = getTabId();
tab.then((value) => {
chrome.scripting.removeCSS({
target: {
tabId: value.id
},
css: css1,
});
chrome.scripting.removeCSS({
target: {
tabId: value.id
},
css: css2,
});
chrome.scripting.removeCSS({
target: {
tabId: value.id
},
css: css3,
});
const respuesta = chrome.tabs.connect(value.id, {
name: "respuesta",
});
respuesta.postMessage(msg);
});
}
}, 1000);
}
async function getTabId() {
let queryOptions = {
active: true,
currentWindow: true
};
let [tab] = await chrome.tabs.query(queryOptions);
return tab;
}
content-script
chrome.runtime.onConnect.addListener(function (port) {
port.onMessage.addListener(function(msg){
if (msg.type === 'SS_UI_REQUEST') {
console.log(msg);
if(!window.stream)
{
var messenger = chrome.runtime.connect();
messenger.postMessage(msg);
}else
{
console.log(msg);
var messenger = chrome.runtime.connect();
messenger.postMessage({ type: 'SS_UI_TAKESCREENSHOT', top: window.scrollY.toString() },'*');
}
}
if (msg.type === 'SS_DIALOG_SUCCESS') {
startScreenStreamFrom(msg.streamId);
console.log(msg);
var messenger = chrome.runtime.connect();
messenger.postMessage({ type: 'SS_UI_TAKESCREENSHOT', top: window.scrollY.toString() },'*');
}
if (msg.type === 'SS_UI_CHANGE_CSS') {
console.log(msg);
}
if (msg.type === 'SS_DIALOG_CANCEL') {
console.log(msg);
}
if(msg.type === "SS_UI_TAKESCREENSHOT_SUCCESS")
{
console.log(msg);
setTimeout(function() {
TakeScreenShot();
}, 300);
}
if(msg.type === "SS_UI_RECORDSCREEN")
{
console.log("Grabar pantalla");
RecordScreen();
}
});
});
function startScreenStreamFrom(streamId) {
console.log("compartiendo pantalla");
navigator.mediaDevices
.getUserMedia({
audio: false,
video: {
mandatory: {
chromeMediaSource: 'desktop',
chromeMediaSourceId: streamId
}
}
})
.then(stream => {
var video = document.getElementById("ElementNotExist");
if(video)
{
video.remove();
}
window.stream = stream;
window.stream.getVideoTracks()[0].onended = function () {
window.stream = null;
};
var video = document.createElement('video');
video.srcObject = stream;
video.type = 'video/ogg';
video.autoplay = true;
video.setAttribute("id","ElementNotExist");
video.style.display = "none";
document.body.appendChild(video);
});
}
Index.js Extension script.
document.getElementById("btn-capture").addEventListener("click", function () {
var tab = getTabId();
tab.then((value) => {
chrome.storage.local.set({ 'pestaƱa': value.id });
const port = chrome.tabs.connect(value.id, {
name: "conexion",
});
port.postMessage({ type: 'SS_UI_REQUEST', text: 'start' }, '*');
window.close();
chrome.action.setPopup({popup: "capture.html"});
});
})
async function getTabId() {
let queryOptions = { active: true, currentWindow: true };
let [tab] = await chrome.tabs.query(queryOptions);
return tab;
}

How to create new img in new div in new header in js?

I want to create slider in js. Here is my code. The problem is how I've mentioned, with creating new img element in new div element in new header element "in the same time", sth. like header > div > img.
const myRequest = new Request('./database.json');
const myHeader = document.querySelector('main');
export const headerTwo = (fragment) => {
fetch(myRequest)
.then(function (response) {
console.warn(response);
return response.json();
})
.then(function () {
let header = document.createElement('div');
// above is the problem with creating header > div > img
header.setAttribute('class', 'slider');
const slideList = [{
img: "https://",
text: 'sth 1'},{
img: "https://",
text: 'sth 2'},{
img: "https://",
text: 'sth 3'}
];
const time = 3000;
let active = 0;
const changeSlide = () => {
active++;
if (active === slideList.length) {
active = 0;
}
header.src = slideList[active].img;
header.textContent = slideList[active].text;
};
let indexInterval = setInterval(changeSlide, time);
myHeader.appendChild(header);
})
.then(function() {
console.log('Co to ????');
})
.catch(function (error) {
console.log('--------- ', error);
});
}
That code should do it
let header = document.createElement('header')
let div = document.createElement('div')
let img = document.createElement('img')
img.setAttribute('src','') // set value
div.appendChild(img)
header.appendChild(div)
Then append header wherever you need it

Categories