If there are many <div>
s in some web page like this:
<div tbinfo="ouid=1234567890&rouid=987654321"></div>
<div tbinfo="ouid=1234567891&rouid=987654321"></div>
<div tbinfo="ouid=1234567892&rouid=987654321"></div>
...
I have this content scripts, trying to remove some division(s) from them, if either ouid
or rouid
matches some key:
var i;
for (i = 0; i < arrID.length; i++) {
chrome.tabs.query(
{active: true}, function(tabs) {
var tab = tabs[0];
let code = `document.querySelectorAll('div[tbinfo]')`;
chrome.tabs.executeScript(tab.id, {code}, function (result) {
const key = arrID[i];
result.forEach(div => {
const tbinfoArr = div.getAttribute('tbinfo');
if (tbinfoArr.includes(key)) {
div.remove();
}
});
});
}
);
}
But chrome says Error handling response: TypeError: div.getAttribute is not a function
What's wrong here?
Suggested by @wOxxOm, I modified my code as below:
for (i = 0; i < arrID.length; i++) {
alert(arrID[0] + ' ' + (typeof arrID[0])); // Alert No.1 // result: 123456789 string
chrome.tabs.query(
{active: true}, function(tabs) {
var tab = tabs[0];
const params = { ID: arrID[i] };
alert(arrID[i] + ' ' + JSON.stringify(params)); // Alert No.2 // result = undefined {}
alert(`(${ removeContent })(${ JSON.stringify(params) })`); // Alert No.4
chrome.tabs.executeScript({
code: `(${ removeContent })(${ JSON.stringify(params) })`
}, ([result] = []) => {
//
});
}
);
}
function removeContent(ID) {
var allElement = document.querySelectorAll('div[tbinfo]');
alert(JSON.stringify(ID)); // Alert No.3
var key = ID.ID;
allElement.forEach(div => {
const tbinfoArr = div.getAttribute('tbinfo');
if (tbinfoArr.includes(key)) {
div.remove();
}
});
return {
success: true,
};
}
alert(JSON.stringify(ID));
shows that ID
parameter is empty (result: {}
).
So I tested ID's value and discovered that // Alert No.1
worked well, but // Alert No.2
was empty.
So it seems like variable outside of chrome.tabs.query(
cannot be referenced inside??
The value of (${ removeContent })(${ JSON.stringify(params) })
is
(function removeContent(ID) {
var allElement = document.querySelectorAll('div[tbinfo]');
var key = ID.ID;
allElement.forEach(div => {
const tbinfoArr = div.getAttribute('tbinfo');
if (tbinfoArr.includes(key)) {
div.remove();
}
});
return {
success: true,
};
}) ({})
This value comes from // Alert No.4
.