Skip to content

Commit

Permalink
Merge pull request #853 from getAlby/feature/lightning-js-events
Browse files Browse the repository at this point in the history
Dispatch JS events when webln is ready and a payment for a lightning link succeeded
  • Loading branch information
bumi authored Jul 11, 2022
2 parents b1934ae + 51dfc79 commit 54feeee
Showing 1 changed file with 39 additions and 6 deletions.
45 changes: 39 additions & 6 deletions src/extension/inpage-script/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@ import WebLNProvider from "../ln/webln";
if (document) {
window.webln = new WebLNProvider();

const readyEvent = new Event("webln:ready");
document.dispatchEvent(readyEvent);

// Intercept any `lightning:` requests
window.addEventListener("click", (ev) => {
const target = ev.target;
Expand All @@ -17,6 +20,7 @@ if (document) {
let href;
let paymentRequest;
let lnurl;
let link; // used to dispatch a succcess event

if (!lightningLink && !bitcoinLinkWithLighting && !lnurlLink) {
return;
Expand All @@ -26,13 +30,16 @@ if (document) {
if (lightningLink) {
href = lightningLink.getAttribute("href").toLowerCase();
paymentRequest = href.replace("lightning:", "");
link = lightningLink;
} else if (bitcoinLinkWithLighting) {
href = bitcoinLinkWithLighting.getAttribute("href");
link = bitcoinLinkWithLighting;
const url = new URL(href);
const query = new URLSearchParams(url.search);
paymentRequest = query.get("lightning");
} else if (lnurlLink) {
href = lnurlLink.getAttribute("href").toLowerCase();
link = lnurlLink;
lnurl = href.replace(/^lnurl[pwc]:/i, "");
}

Expand All @@ -54,16 +61,42 @@ if (document) {
if (!response.enabled) {
return;
}

if (lnurl) {
return window.webln.lnurl(lnurl).catch((e) => {
console.error(e);
alert(`Error: ${e.message}`);
});
return window.webln
.lnurl(lnurl)
.catch((e) => {
console.error(e);
if (
![ABORT_PROMPT_ERROR, USER_REJECTED_ERROR].includes(e.message)
) {
alert(`Error: ${e.message}`);
}
})
.then((response) => {
const responseEvent = new CustomEvent("lightning:success", {
bubbles: true,
detail: {
lnurl,
response,
},
});
link.dispatchEvent(responseEvent);
});
}

return window.webln
.sendPayment(paymentRequest)
.then((r) => {
console.info(r);
.then((response) => {
console.info(response);
const responseEvent = new CustomEvent("lightning:success", {
bubbles: true,
detail: {
paymentRequest,
response,
},
});
link.dispatchEvent(responseEvent);
})
.catch((e) => {
console.error(e);
Expand Down

0 comments on commit 54feeee

Please sign in to comment.