I am building a chrome extension that captures the screenshot (tab) on clicking, say, hyperlink. The current Tab is not being captured if a new tab opens on clicking the hyperlink or a button.
Error:
Unchecked runtime.lastError: Cannot access contents of URL "". Extension manifest must request permission to access this host.
How can I capture the current tab in this scenario (not the new tab)?
In the example below, dataUrl
(screenshot data) will be null if clicked on the first link.
The new tab opens quickly, and by the time function is being executed in the background script, the focus is on the new tab (see current tab id).
To reproduce:
index.html
<a id="first" href="https://www.example.org" target="_blank">Open link in new tab</a> <br>
<a id="second" href="https://www.example.org">Open link in same tab</a>
manifest.json
...
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["content.js"],
"css": ["content.css"]
}
],
"host_permissions": ["<all_urls>","*://localhost:8080/*"],
"permissions": [
"activeTab",
"tabs"
],
...
content.js
/////////////// Capture tab on mouse click ///////////////
document.addEventListener("click", (e) => {
chrome.runtime.sendMessage({ msg: "capture"}, function (response) {
});
console.log("inside click eventListener");
}, true);
background.js
chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
console.log("Current tab id", tabs[0].id);
console.log("Sender tab id", sender.tab.id);
});
chrome.tabs.captureVisibleTab(
null,
{
format: "png",
quality: 100,
},
function (dataUrl) {
console.log(dataUrl);
}
);
return true;
});
Please let me know if you need additional details. Thanks in advance!