Answer the question
In order to leave comments, you need to log in
Why doesn't my browser extension script work on some sites?
Hello. I have a simple browser extension.
I want to catch the moment of pressing a button on a certain site, but it does not work.
The strange thing is that I catch the button by the id assigned to the desired button, but it works on one site, but not on another site.
What could be the problem?
{
"manifest_version": 2,
"name": "test",
"version": "1.0.0",
"content_scripts": [
{
"matches": ["*://*.mysite.ru/*"],
"js": ["jquery.js", "content.js"]
}
],
"browser_action": {
"default_icon": "favicon.ico"
}
}
$(document).ready(function(){
$("#button_id" ).click(function(){
alert("HELLO");
});
});
<a href="#" id="button_id">test</a>
Answer the question
In order to leave comments, you need to log in
Most likely, the problem is that at the time of running the code from content.js , your button is still missing from the page.
I will give you a clicker function from one of my extensions, use it:
function clickElements(selector, regexp, where) {
return new Promise(function(returnResult) {
var search_result = false;
var local_reactive_function = function() {
var click_elements = searchElements(selector, regexp, where);
if (click_elements.length > 0) {
if (search_result === false) {
search_result = true;
observer.disconnect();
setTimeout(function() {
var click_elements = searchElements(selector, regexp, where);
for (var n = 0; n < click_elements.length; n++) {
click_elements[n].click();
}
returnResult(click_elements.length);
}, 1000);
}
}
}
var observer = new MutationObserver(local_reactive_function);
observer.observe(document.body, {
characterData: true,
attributes: true,
childList: true,
subtree: true
});
local_reactive_function();
});
}
function searchElements(selector, regexp, where) {
var search_elements = [];
if (typeof where !== 'undefined') {
var all_elements = where.querySelectorAll(selector);
}
else {
var all_elements = document.querySelectorAll(selector);
}
for (var n = 0; n < all_elements.length; n++) {
if (typeof regexp == 'object') {
if (typeof regexp.test == 'function') {
if (regexp.test(all_elements[n].innerText.trim())) {
search_elements.push(all_elements[n]);
}
}
}
else {
search_elements.push(all_elements[n]);
}
}
return search_elements;
}
(async function() {
await clickElements('CSS-селектор 1');
await clickElements('CSS-селектор 2');
await clickElements('CSS-селектор 3');
})();
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question