Cancel Payment Button in paystack not working - javascript

I am implementing payment gateway with paystack for the first time and I really don't want to use third party packages for paystack. It is a React Native application. I wanted to implement it using react native webview. It is working so far but I can't seem to get the cancel button to work. This is because the button is not responding when clicked. If the button responded and invoked the paystack onClose URL https://standard.paystack.co/close, I would have simply checked for it and close the webview state.
So, how do I handle this? The button can't be there without doing anything. Can I use javascript and hide it and create my own custom button that actually works on click?: Here is the code I have tried so far:
const { url } = value
if (!url) return;
webView.current.injectJavaScript(handleCancle)
const customUrl = url.split('?');
const getCallBackURL = customUrl[0];
const queryStr = customUrl[1]
if(getCallBackURL == callback_url){
setPaymentState(false);
try {
const res = await axios.get(`${BASE_URL}/payverify/?${queryStr}`);
if(res?.data?.status == 'success'){
const payMentData = res?.data
navigation.navigate('ThankyouPage', {payMentData})
}
} catch (error) {
}
}
The code that tried listening to button click but not working:
const handleCancle = `
var buttons = document.getElementsByTagName('button');
buttons.forEach((button)=>{
if(button.innerHTML.includes('Cancel Payment')){
button.addEventListener("click", function() {
console.log('it has happened')
var resp = {event:'cancelled'};
window.ReactNativeWebView.postMessage(JSON.stringify(resp))
});
}
})
}
`
The webview:
{
isPaymentSuccess && paymentState &&
<WebView
javaScriptEnabled={true}
source={{ uri: paymentData }}
style={{ marginTop: 50 }}
onNavigationStateChange={ handleNav }
cacheEnabled={false}
cacheMode={'LOAD_NO_CACHE'}
ref={webView}
onMessage={(e) => {
console.log('pressed')
console.log(e.nativeEvent?.data)
}}
/>
}
The error so far: No error. No response when the cancel button is clicked!

Related

Does anyone know why this code is not working the way I want it to?

I am creating a web app with node.js, express and pug templates and here I am trying to simulate a warning when the user tries to remove a review he has posted.
so, in the front end I have a button that the user clicks to remove his review
when the user clicks that button I run
index.js
import { showWarning } from './warning';
const removerStoreReviewBtn = document.querySelector('.side-nav__removeStoreReviewbtn');
if (removerStoreReviewBtn)
removerStoreReviewBtn.addEventListener('click', e => {
e.preventDefault();
showWarning('Would you like to remove this review ?');
});
warning.js
export const hideWarning = () => {
const el = document.querySelector('.warning');
const warningText = document.querySelector('.warning__text');
if (el) el.parentElement.removeChild(el);
if (warningText) warningText.parentElement.removeChild(warningText);
};
export const showWarning = (msg, time = 30) => {
hideWarning();
console.log(msg);
const markUp = `
<div class="warning">
<div class="warning__text">${msg}</div>
<button class="warning--no">
<span>Cancelar</span>
</button>
<button class="warning--yes">
<span>Apagar</span>
</button>
</div>`;
document.querySelector('.header').insertAdjacentHTML('afterend', markUp);
window.setTimeout(hideWarning, time * 1000);
};
The showWarning function display everything the way I want in the front end
then back at the index.js file I have the following code
index.js
const warningBtnYes = document.querySelector('.warning--yes');
const warningBtnNo = document.querySelector('.warning--no');
if (warningBtnYes)
warningBtnYes.addEventListener('click', e => {
e.preventDefault();
console.log('remove');
//removerStoreReview(reviewId);
});
if (warningBtnNo)
warningBtnNo.addEventListener('click', e => {
e.preventDefault();
console.log('Do not remove');
});
when I click any of these buttons nothing happens (I am expecting the console.logs) and I can't figure out why nothing happens, hopefully anyone can help me.
Thanks
Mateus
When you use .parentElement.removeChild() you have turned off all event listeners for those button.
You have two options. You can preserve the event listeners by storing the return value from the .removeChild() call. In order to restore the event listeners you will need to reuse the stored (previously removed) node.
Alternatively, you'll need to re-add your event listeners after inserting the new HTML.
Helpful docs

How to call function on Safari after page load?

I need to redirect the web page after it loads and gets the param from the URL. I can do this with a button click.
However, I want to redirect the page automatically (without user input so better UX). Here I use window.addEventListener('load', () => handleClick()) and it works well on Chrome, but it does not always fire on Safari (desktop and mobile).
I can debug this by adding alert('Beginning'); in the handler — on Chrome, this fires automatically after the page load, but not on Safari.
How I can solve this?
const handleClick = async (event) => {
alert('Beginning'); //For debugging
const stripe = await stripePromise;
const { error } = await stripe.redirectToCheckout({
param,
});
}
if (typeof window !== `undefined`) {
const param = new URLSearchParams(window.location.search).get('param');
}
const Page = () => {
if (typeof window !== `undefined`) {
window.addEventListener('load', () => handleClick())
}
return (
<section >
<button role="link" onClick={handleClick}> //Only for fallback
Press
</button>
</section>
);
};
export default Page;
Without clicking the button you can use history.push function.Since it fires as soon as it is called.
history.push(location)

How do I make a tab highlight with React

I want to know how to make a Tab highlight everytime an event happens, in this case, it would be a call. So, if the user isn't in my website in the moment, he will know that a event happenned. My useEffect looks like the following:
useEffect(() => {
if (newCall < calls.length){
setHighlight(true)
setNewCall(calls.length)
}
}, [calls.length])
useEffect(() => {
if (newCall < calls.length){
setHighlight(!'your state name')
setInterval(()=>setHighlight(!'your state name'),2000)
setNewCall(calls.length)
}
}, [calls.length])
The above fragment of code sets highlight and so does the user knows that an event has happened and after 2 seconds the highlight will be returned to the initial state.
It seems as though the solution is a combination of:
Browser tab change notification like when you get a new gmail e-mail or a new tweet in Twitter
and
Detect If Browser Tab Has Focus
useEffect(() => {
window.onfocus = function(){
document.title = "Original Title"
}
return () => {
window.onfocus = null;
}
}, []);
useEffect(() => {
if (newCall < calls.length){
document.title = `Original Title (${calls.length} calls)`
}
}, [calls.length])

How to get the buttons in a 'dialog.showMessageBoxSync' to work in Electron.js

In my electron application, I have a .showMessageBoxSync message box with two buttons that displays if the user doesn't have a internet connection or not. The message box itself works, but the buttons on the box won't fire the functions like it is supposed to. When I click "Try again please" button, the box just closes. It does the same with the other button. I'd like to test the internet connection again if the user would like to, so I tried to call the 'execute()' method again, but to no avail.
Here is my code -
function secondOnline(user_callback){
const message = () => {
return dialog.showMessageBoxSync(null, {
title:"Connection Status",
message:"No internet available, do you want to try again?",
type:'warning',
buttons:["Try again please","No, thanks"]
}, (result) => {
if(result === 0){
execute();
}
})
};
const secondMessage = () => {
return dialog.showMessageBoxSync({
title:"Connection Status",
message:"Internet connected.",
type:'info'})
};
const execute = () => {
if(navigator.onLine){
secondMessage()
}else{
message();
}
};
execute();
}
Any ideas?
Thanks.

Selenium Get Element After Following Link

all!
I've followed as many tips and tutorials as I can, but I can't figure out how to obtain an element in Node JS Selenium after moving from the starting page.
In my use case, I go to a login screen, enter the pertinent information, and then run a click() on the login button. I am taken to the home screen.
After this, I cannot select any elements! I just keep getting 'not found' warnings.
I'm sleeping for 6000ms, and I have set the implicit timeouts to 30s.
What am I missing here?
My problematic part would be in the function GoToSettings, which is called after the Login button is clicked.
Thanks
var webdriver = require('selenium-webdriver'),
By = webdriver.By,
until = webdriver.until;
const TIMEOUT = 30
var driver = new webdriver.Builder().forBrowser('chrome').build();
const capabilities = driver.getCapabilities().then(()=>{
capabilities['map_'].set('timeouts', { implicit: TIMEOUT, pageLoad: TIMEOUT, script: TIMEOUT });
});
var info = require('./info.json')
driver.get('http://www.okcupid.com/settings?')
driver.sleep(2000);
//We may already be logged in at this point
driver.getTitle().then((title) => {
driver.getCurrentUrl().then((url) => {
LoginOrHome(title, url);
});
});
function LoginOrHome(title, url){
if(title == "Free Online Dating | OkCupid" || url == "https://www.okcupid.com/login?p=/settings") {
//needslogin.exe
console.log("Logging in!");
login();
} else if (title == "Welcome! | OkCupid" || url == "https://www.okcupid.com/settings?") {
//We are already logged in
console.log("Already logged in. Changing location.");
goToSettings();
} else {
console.log(title);
console.log(url);
}
}
function goToSettings() {
driver.sleep(6000);
driver.switchTo().window(driver.getWindowHandle()).then( () => {
driver.getCurrentUrl().then((title) => {
//This prints the URL of the previous page
console.log(title);
});
})
}
function login(){
driver.findElement(By.name("username")).sendKeys(info.email).then(() => {
driver.findElement(By.name("password")).sendKeys(info.password).then(() => {
driver.findElement(By.css("div > input[type=submit]")).click().then(()=> { goToSettings() });
});
});
}

Categories

Resources