In manifest v2 this code worked and injected the script when button was clicked:
popup.js v2 (works)
JavaScript
x
13
13
1
document.addEventListener('DOMContentLoaded', function () {
2
// Get button by ID
3
var button = document.getElementById('btnScan');
4
5
// Define button on click action
6
button.onclick = function () {
7
chrome.tabs.executeScript(null, {
8
file: 'Scripts/script.js'
9
});
10
window.close();
11
}
12
});
13
Now in manifest v3, chrome.tabs.executeScript
is replaced with chrome.scripting.executeScript
.
scripting
permission is added in manifest.json
.
popup.js v3 (not working)
JavaScript
1
17
17
1
document.addEventListener('DOMContentLoaded', function () {
2
// Get button by ID
3
var button = document.getElementById('btnScan');
4
5
// Define Scan button on click action
6
button.onclick = function () {
7
chrome.scripting.executeScript
8
(
9
{
10
target: { tabId: null}, // ???????
11
files: ['Scripts/script.js']
12
}
13
);
14
window.close();
15
}
16
});
17
The problem is that chrome.tabs.executeScript
requires tabId
value as one of the parameters.
How can I get tabId
value in popup.js
or convert the manifest v2 version javascript so that it works the same?
Advertisement
Answer
Thanks to @wOxxOm who posted a link as a comment.
The solution was to get the active tab and use its tabId
.
JavaScript
1
15
15
1
document.addEventListener('DOMContentLoaded', function () {
2
// Get button by ID
3
var button = document.getElementById('btnScan');
4
button.onclick = injectScript;
5
});
6
7
async function injectScript() {
8
const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
9
await chrome.scripting.executeScript({
10
target: { tabId: tab.id },
11
files: ['Scripts/script.js']
12
});
13
window.close();
14
}
15