On the web page I'm working on, clicking on the link occurs due to the function sendEvent('openassignment','mx145','0'), the link number is passed in the third parameter of this function, 0 is the first link, 1 is the second link, 2 is the third link, etc. I need to programmatically check if the link exists. For example, there is no link number 30 on the page, how do I check it?
I need to implement: if I followed the link, then we output "everything is ok" if the link is missing, then there will be no transition, and then how to catch this moment?
const myTask = () => new Promise(resolve => {
resolve(sendEvent('openassignment', 'mx145', '0'));
});
async function myt() {
await myTask().then(() => {
// if I followed the link, then we output "everything is ok"
// if the link is missing, then there will be no transition, and then how to catch this moment?
});
}
myt();
First select the nth-of-type link by using document.querySelector. This allows us to target a specific link and see if it exists and has a href property.
Then make a fetch request with the href value and see if you get a successful response. If response.ok is true, then the link exists.
async function checkNthOfLink(numberOfLink) {
const link = document.querySelector(`a:nth-of-type(${numberOfLink})`);
if (link === null || !link.href) {
return false;
}
const { ok } = await fetch(link.href, {
method: 'HEAD'
});
return ok;
}
You can use it like here below. The result value will either be true or false. Based on that you can call your sendEvent function.
checkNumberOfLink(30).then(result => {
if (result === true) {
sendEvent('openassignment', 'mx145', '30')
}
});