Using MutationObserver to wait for button to appear - javascript

I am trying to create something that automatically clicks the required buttons on stackexchange type sites so that I can stop doing it myself. I am using a content script. I am trying to:
Find the button to customize cookies
click accept (they're usually all deselected with stackexchange sites)
Here is my code so far. I think it finds the right node, but clicks it too soon? I am not entirely sure since I'm new to js and whatnot.
function AcceptCustomization() {
let myNode;
let observer = new MutationObserver((mutations) => {
mutations.forEach((mutation) => {
if (!mutation.addedNodes) return
for (let i = 0; i < mutation.addedNodes.length; i++) {
// do things to your newly added nodes here
let node = mutation.addedNodes[i]
if (node.nodeType === 1) {
node
var a = node.getElementsByClassName("flex--item s-btn s-btn__primary save-preference-btn-handler onetrust-close-btn-handler js-consent-banner-hide js-consent-save")[0]
if (a) {
myNode = a
console.log(myNode)
console.log(myNode.click())
}
}
}
})
})
observer.observe(document.body, {
childList: true
, subtree: true
, attributes: false
, characterData: false
})
}
function CustomizeCookies() {
var a = document.getElementsByClassName("flex--item s-btn s-btn__filled js-cookie-settings")[0];
if (a) {
a.click();
AcceptCustomization();
}
else {
console.log(a);
}
}
CustomizeCookies();
In the future, I want to create an extension that I can use to create a sort of database of websites with corresponding button clicks. For example, if I don't have the cookie customization for a website, I would click the extension and run a script that captures my button clicks and redoes them every future time I visit (if it is not the same session).
Thanks :)

Related

chrome.tabs.update stops working when called from extension

I tried the following code. It basically takes a screenshot from all tabs open in the current window:
function captureWindowTabs(windowId, callbackWithDataUrlArray) {
var dataUrlArray = [];
// get all tabs in the window
chrome.windows.get(windowId, { populate: true }, function(windowObj) {
var tabArray = windowObj.tabs;
// find the tab selected at first
for(var i = 0; i < tabArray.length; ++i) {
if(tabArray[i].active) {
var currentTab = tabArray[i];
break;
}
}
// recursive function that captures the tab and switches to the next
var photoTab = function(i) {
chrome.tabs.update(tabArray[i].id, { active: true }, function() {
chrome.tabs.captureVisibleTab(windowId, { format: "png" }, function(dataUrl) {
// add data URL to array
dataUrlArray.push({ tabId:tabArray[i].id, dataUrl: dataUrl });
// switch to the next tab if there is one
if(tabArray[i+1]) {
photoTab(i+1);
}
else {
// if no more tabs, return to the original tab and fire callback
chrome.tabs.update(currentTab.id, { active: true }, function() {
callbackWithDataUrlArray(dataUrlArray);
});
}
});
});
};
photoTab(0);
});
}
When I call this code from popup.html opened as a webpage, it works as expected (I trigger this from a button click in the popup.html). When I call it from the browser extension, it just gets interrupted from the first tab it selects. Any idea why that is? I can't share errors, since the debugger gets closed when called from the extension.
Supplementary, is there a way to achieve desired result without needing the visual tab switching?
While updating the next tab as active tab. make sure current tab is no more active tab by doing
chrome.tabs.update(tabArray[i-1].id, { active: false }, ()=>{});
Moving the extension to a background script fixed the problem.
Reasoning is that the popup will close once the tab switches. Hence it is required to run in the background where it is not interrupted when the popup closes.

When to disconnect MutationObserver in Chrome / Web Extension?

I want to know when or if I need to disconnect a MutationObserver in my content script to avoid memory leaks.
So my content script checks all new additions to the DOM and updates the HTML accordingly. I use a MutationObserver for this which is created and started at in the content script.
My question is, does the MutationObserver destroy itself when a new page is loaded or must I listen to page changes to disconnect it and destroy it myself each time.
Here is the relevant code:
function startObserver(textSize: number, lineHeight: number, font: string = "Droid Arabic Naskh") {
let config: MutationObserverInit = {
attributes: false,
childList: true,
subtree: true,
characterData: true,
characterDataOldValue: false,
};
let callback: MutationCallback = (mutationsList: MutationRecord[]) => {
mutationsList.forEach((record: MutationRecord) => {
// If something has been added
if (record.addedNodes.length > 0) {
// For each added node
record.addedNodes.forEach((addedNode: Node) => {
// For each node with Arabic script in addedNode
getArabicTextNodesIn(addedNode).forEach((arabicNode: Node) => {
// Update arabicNode only if it hasn't been updated
if (arabicNode.parentElement && arabicNode.parentElement.getAttribute("class") != "ar") {
updateNode(arabicNode, textSize, lineHeight, font);
}
});
});
}
});
};
if (!observer) {
observer = new MutationObserver(callback);
observer.observe(document.body, config);
}
}
Found it out a long time ago thanks to #xOxxm and some personal testing and playing around but answering myself in case someone else needs this in the future
Does the MutationObserver destroy itself when a new page is loaded or must I listen to page changes to disconnect it and destroy it myself each time?
Yes the MutationObserver destroys itself upon leaving the page (the document has changed) so the above code was in fact safe and devoid of any possible memory leaks.

How to check if dynamic elements are available/loaded yet?

I have a javascript that uses document.querySelector() to retrieve text content from div/span elements - these are dynamically loaded. For example, user name is always available in the DOM. When the user comes online, an additional span is created indicating the IP address from which he is currently logged in; it disappears as soon as the user logs out.
So when the IP location element is not available in DOM, the console.log is not printing anything -
function f(){
try{ b=document.querySelector("#main > header > div>div>span").textContent,
name=document.querySelectorAll("#main > header > div>div>div>span")[1].textContent
}catch(e){return}
console.log(name + ", " + b)}
interval=setInterval(f,1000);
I want to capture each time the user logs in, and triggers the IP location element to display; or I want to write the if condition that checks whether the IP location span has been created in the DOM or not.
Please note, the script also runs setInterval() to check when the user is online.
You can use MutationObserver to check for changes in a node.
Here's an example:
const divObservable = document.getElementById('observable');
const btnAdd = document.getElementById('btn-add');
const btnRemove = document.getElementById('btn-remove');
btnAdd.addEventListener('click', () => {
setTimeout(() => {
divObservable.innerHTML = `<span>Hello, World!</span>`;
}, 2000);
});
btnRemove.addEventListener('click', () => {
setTimeout(() => {
divObservable.innerHTML = '';
}, 2000);
});
const observerConfig = {
attributes: true,
childList: true,
subtree: true,
};
const observerCallback = (mutationsList, observer) => {
for (var mutation of mutationsList) {
if (mutation.type === 'childList') {
console.log('A child node has been added or removed.');
}
}
};
const observer = new MutationObserver(observerCallback);
observer.observe(divObservable, observerConfig);
console.log('observing');
<div id="observable"></div>
<button id="btn-add">Async Add Span</button>
<button id="btn-remove">Async Remove Span</button>
Just check in the childList mutation if the IP location exists or not.
Since I am using setInterval in my script, I made further use of it in this scenario by checking the childElementCount -
target=document.getElementsByClassName("_3V5x5")[0].childElementCount;
if(target===2){
//IP location may be available now
} else {
// User is offline
}

detect when challenge window is closed for Google recaptcha

I am using Google invisible recaptcha. Is there a way to detect when the challenge window is closed? By challenge window I mean window where you have to pick some images for verification.
I currently put a spinner on the button that rendered the recaptcha challenge, once the button is clicked. There is no way for the user to be prompted with another challenge window.
I am calling render function programmatically:
grecaptcha.render(htmlElement, { callback: this.verified, expiredCallback: this.resetRecaptcha, sitekey: this.siteKey, theme: "light", size: "invisible" });
I have 2 callback functions wired up the verified and the resetRecaptcha functions which look like:
function resetRecaptcha() {
grecaptcha.reset();
}
function verified(recaptchaResponse)
{
/*
which calls the server to validate
*/
}
I would have expected that grecaptcha.render has another callback that is called when the challenge screen is closed without the user verifying himself by selecting the images.
As you mention, the API doesn't support this feature.
However, you can add this feature yourself. You may use the following code with caution, Google might change its reCaptcha and by doing so break this custom code. The solution relies on two characteristics of reCaptcha, so if the code doesn't work, look there first:
the window iframe src: contains "google.com/recaptcha/api2/bframe"
the CSS opacity property: changed to 0 when the window is closed
// to begin: we listen to the click on our submit button
// where the invisible reCaptcha has been attachtted to
// when clicked the first time, we setup the close listener
recaptchaButton.addEventListener('click', function(){
if(!window.recaptchaCloseListener) initListener()
})
function initListener() {
// set a global to tell that we are listening
window.recaptchaCloseListener = true
// find the open reCaptcha window
HTMLCollection.prototype.find = Array.prototype.find
var recaptchaWindow = document
.getElementsByTagName('iframe')
.find(x=>x.src.includes('google.com/recaptcha/api2/bframe'))
.parentNode.parentNode
// and now we are listening on CSS changes on it
// when the opacity has been changed to 0 we know that
// the window has been closed
new MutationObserver(x => recaptchaWindow.style.opacity == 0 && onClose())
.observe(recaptchaWindow, { attributes: true, attributeFilter: ['style'] })
}
// now do something with this information
function onClose() {
console.log('recaptcha window has been closed')
}
As I mentioned in the comments of the answer submitted by #arcs, it is a good solution which works but it also fires onClose() when the user successfully completes the challenge. My solution is to change the onClose() function like so:
// now do something with this information
function onClose() {
if(!grecaptcha.getResponse()) {
console.log('recaptcha window has been closed')
}
}
This way, it only executes the desired code if the challenge has been closed and it has not been completed by the user, thus the response cannot be returned with grecaptcha.getResponse()
The drawback of detecting when iframe was hidden is that it fires not only when user closes captcha by clicking in background, but also when he submits the answer.
What I needed is detect only the first situation (cancel captcha).
I created a dom observer to detect when captcha is attached to DOM, then I disconnect it (because it is no longer needed) and add click handler to its background element.
Keep in mind that this solution is sensitive to any changes in DOM structure, so if google decides to change it for whatever reason, it may break.
Also remember to cleanup the observers/listeners, in my case (react) I do it in cleanup function of useEffect.
const captchaBackgroundClickHandler = () => {
...do whatever you need on captcha cancel
};
const domObserver = new MutationObserver(() => {
const iframe = document.querySelector("iframe[src^=\"https://www.google.com/recaptcha\"][src*=\"bframe\"]");
if (iframe) {
domObserver.disconnect();
captchaBackground = iframe.parentNode?.parentNode?.firstChild;
captchaBackground?.addEventListener("click", captchaBackgroundClickHandler);
}
});
domObserver.observe(document.documentElement || document.body, { childList: true, subtree: true });
To work in IE this solution needs polyfills for .include() and Array.from(), found below:
Array.from on the Internet Explorer
ie does not support 'includes' method
And the updated code:
function initListener() {
// set a global to tell that we are listening
window.recaptchaCloseListener = true
// find the open reCaptcha window
var frames = Array.from(document.getElementsByTagName('iframe'));
var recaptchaWindow;
frames.forEach(function(x){
if (x.src.includes('google.com/recaptcha/api2/bframe') ){
recaptchaWindow = x.parentNode.parentNode;
};
});
// and now we are listening on CSS changes on it
// when the opacity has been changed to 0 we know that
// the window has been closed
new MutationObserver(function(){
recaptchaWindow.style.opacity == 0 && onClose();
})
.observe(recaptchaWindow, { attributes: true, attributeFilter: ['style'] })
}
My solution:
let removeRecaptchaOverlayEventListener = null
const reassignGRecatchaExecute = () => {
if (!window.grecaptcha || !window.grecaptcha.execute) {
return
}
/* save original grecaptcha.execute */
const originalExecute = window.grecaptcha.execute
window.grecaptcha.execute = (...params) => {
try {
/* find challenge iframe */
const recaptchaIframe = [...document.body.getElementsByTagName('iframe')].find(el => el.src.match('https://www.google.com/recaptcha/api2/bframe'))
const recaptchaOverlay = recaptchaIframe.parentElement.parentElement.firstElementChild
/* detect when the recaptcha challenge window is closed and reset captcha */
!removeRecaptchaOverlayEventListener && recaptchaOverlay.addEventListener('click', window.grecaptcha.reset)
/* save remove event listener for click event */
removeRecaptchaOverlayEventListener = () => recaptchaOverlay.removeEventListener('click', window.grecaptcha.reset)
} catch (error) {
console.error(error)
} finally {
originalExecute(...params)
}
}
}
Call this function after you run window.grecaptcha.render() and before window.grecaptcha.execute()
And don't forget to remove event listener: removeRecaptchaOverlayEventListener()
For everybody that didn't quite get how it all works, here is another example with explanations that you might find useful:
So we have 2 challenges here.
1) Detect when the challenge is shown and get the overlay div of the challenge
function detectWhenReCaptchaChallengeIsShown() {
return new Promise(function(resolve) {
const targetElement = document.body;
const observerConfig = {
childList: true,
attributes: false,
attributeOldValue: false,
characterData: false,
characterDataOldValue: false,
subtree: false
};
function DOMChangeCallbackFunction(mutationRecords) {
mutationRecords.forEach((mutationRecord) => {
if (mutationRecord.addedNodes.length) {
var reCaptchaParentContainer = mutationRecord.addedNodes[0];
var reCaptchaIframe = reCaptchaParentContainer.querySelectorAll('iframe[title*="recaptcha"]');
if (reCaptchaIframe.length) {
var reCaptchaChallengeOverlayDiv = reCaptchaParentContainer.firstChild;
if (reCaptchaChallengeOverlayDiv.length) {
reCaptchaObserver.disconnect();
resolve(reCaptchaChallengeOverlayDiv);
}
}
}
});
}
const reCaptchaObserver = new MutationObserver(DOMChangeCallbackFunction);
reCaptchaObserver.observe(targetElement, observerConfig);
});
}
First, we created a target element that we would observe for Google iframe appearance. We targeted document.body as an iframe will be appended to it:
const targetElement = document.body;
Then we created a config object for MutationObserver. Here we might specify what exactly we track in DOM changes. Please note that all values are 'false' by default so we could only leave 'childList' - which means that we would observe only the child node changes for the target element - document.body in our case:
const observerConfig = {
childList: true,
attributes: false,
attributeOldValue: false,
characterData: false,
characterDataOldValue: false,
subtree: false
};
Then we created a function that would be invoked when an observer detects a specific type of DOM change that we specified in config object. The first argument represents an array of Mutation Observer objects. We grabbed the overlay div and returned in with Promise.
function DOMChangeCallbackFunction(mutationRecords) {
mutationRecords.forEach((mutationRecord) => {
if (mutationRecord.addedNodes.length) { //check only when notes were added to DOM
var reCaptchaParentContainer = mutationRecord.addedNodes[0];
var reCaptchaIframe = reCaptchaParentContainer.querySelectorAll('iframe[title*="recaptcha"]');
if (reCaptchaIframe.length) { // Google reCaptcha iframe was loaded
var reCaptchaChallengeOverlayDiv = reCaptchaParentContainer.firstChild;
if (reCaptchaChallengeOverlayDiv.length) {
reCaptchaObserver.disconnect(); // We don't want to observe more DOM changes for better performance
resolve(reCaptchaChallengeOverlayDiv); // Returning the overlay div to detect close events
}
}
}
});
}
Lastly we instantiated an observer itself and started observing DOM changes:
const reCaptchaObserver = new MutationObserver(DOMChangeCallbackFunction);
reCaptchaObserver.observe(targetElement, observerConfig);
2) Second challenge is the main question of that post - how do we detect that the challenge is closed? Well, we need help of MutationObserver again.
detectReCaptchaChallengeAppearance().then(function (reCaptchaChallengeOverlayDiv) {
var reCaptchaChallengeClosureObserver = new MutationObserver(function () {
if ((reCaptchaChallengeOverlayDiv.style.visibility === 'hidden') && !grecaptcha.getResponse()) {
// TADA!! Do something here as the challenge was either closed by hitting outside of an overlay div OR by pressing ESC key
reCaptchaChallengeClosureObserver.disconnect();
}
});
reCaptchaChallengeClosureObserver.observe(reCaptchaChallengeOverlayDiv, {
attributes: true,
attributeFilter: ['style']
});
});
So what we did is we get the Google reCaptcha challenge overlay div with the Promise we created in Step1 and then we subscribed for "style" changes on overlay div. This is because when the challenge is closed - Google fade it out.
It's important to note that the visibility will be also hidden when a person solves the captcha successfully. That is why we added !grecaptcha.getResponse() check. It will return nothing unless the challenge is resolved.
This is pretty much it - I hope that helps :)

How to stop a new node being added to DOM using Chrome/Firefox extension?

I am writing an extension to detect some malicious behavior of some scripts. These scripts add some nodes into the DOM after page gets loaded. I am able to get these nodes using
document.addEventListener("DOMNodeInserted", checkContents, false);
But how can I stop them from being loaded? Can this be done in Chrome or Firefox?
Use MutationObserver with childList and subtree.
var grid = iframe.contentDocument.getElementById('newtab-grid');
var mobs = new iframe.contentWindow.MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
console.log(mutation.type, mutation);
if (mutation.addedNodes && mutation.addedNodes.length > 0) {
var link = mutation.target.querySelector('.newtab-link');
if (link) {
link.setAttribute('target', '_parent');
console.log('set target on this el')
} else {
console.log('this ell has no link BUT it was an added el')
}
}
});
});
mobs.observe(grid, {
childList: !0,
subtree: !0
});
now this will tell you when its addingNodes and it gives you what was added in mutation.addedNodes. you can iterate throuh that and remove what was added. I'm not sure if you can prevent it from adding, but you can definitely remove it after it was added.
https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver?redirectlocale=en-US&redirectslug=DOM%2FMutationObserver#MutationObserverInit

Categories