62 lines
1.9 KiB
JavaScript
62 lines
1.9 KiB
JavaScript
function findATagsAndAddListener(el) {
|
|
let tags = [];
|
|
|
|
// Google has elements that prevent click on links. May need different handling
|
|
// if (window.location.href.indexOf("google.") >= 0) {
|
|
// const elements = document.getElementsByClassName("NqpkQc");
|
|
// while(elements.length > 0){
|
|
// elements[0].parentNode.removeChild(elements[0]);
|
|
// }
|
|
// }
|
|
|
|
if (window.location.href.indexOf('youtube.com') >= 0) {
|
|
tags = el.querySelectorAll('a[href*="/watch"]');
|
|
} else {
|
|
tags = el.querySelectorAll('a[href*="youtube.com/"]');
|
|
}
|
|
|
|
for (i = 0; i < tags.length; i++) {
|
|
addListenerToATag(tags[i]);
|
|
}
|
|
}
|
|
|
|
function addListenerToATag(tag) {
|
|
tag.addEventListener('click', function(e) {
|
|
e.preventDefault();
|
|
e.stopImmediatePropagation();
|
|
|
|
// Find the a tag
|
|
var target = e.target;
|
|
while ((target.tagName != "A" || !target.href) && target.parentNode) {
|
|
target = target.parentNode;
|
|
}
|
|
|
|
let targetName = (target.attributes.target != null ? target.attributes.target.nodeValue : '_self')
|
|
if (e.ctrlKey || e.metaKey) {
|
|
targetName = "_blank";
|
|
}
|
|
|
|
browser.runtime.sendMessage({"url": target.href, "targetName": targetName});
|
|
})
|
|
}
|
|
|
|
// Add the event listeners to the current elements of the body
|
|
findATagsAndAddListener(document.body);
|
|
|
|
// Monitor the DOM for additions and create event listeners on the go
|
|
const observer = new MutationObserver((mutations) => {
|
|
mutations.forEach((mutation) => {
|
|
if (mutation.addedNodes && mutation.addedNodes.length > 0) {
|
|
for (let i = 0; i < mutation.addedNodes.length; i++) {
|
|
const newNode = mutation.addedNodes[i];
|
|
if (newNode.nodeType === Node.ELEMENT_NODE || newNode.nodeType === Node.DOCUMENT_NODE || newNode.nodeType === Node.DOCUMENT_FRAGMENT_NODE) {
|
|
findATagsAndAddListener(newNode);
|
|
}
|
|
}
|
|
}
|
|
});
|
|
});
|
|
observer.observe(document.body, {
|
|
childList: true,
|
|
subtree: true
|
|
}); |