EDIT: Resolved. Turns out I just had to add <all_urls> to the “host_permissions”, which is odd, because I already had https and http added there, along with the hostname of my processing server. Consider the matter closed.
I’ve been developing an extension whose functions include the user clicking on a Report button, injected by the content script. That Report button is supposed to trigger a function in the background service worker ( background.js ), that would save the page in the current tab as MHTML, capture a PNG screenshot of the current tab, zip both files and send the resulting zip to a remote script for analysis via a fetch() request.
However, when I try testing it, I end up with “Unchecked runtime.lastError: Either the ‘<all_urls>’ or ‘activeTab’ permission is required. ( even though I have “activeTab” in permissions )”. Even though the activeTab permission is CLEARLY configured in manifest.json, along with the tabs permission.
I am including all the relevant code in both content.js and background.js.
content.js relevant code:
// Function to request the background script to capture MHTML and PNG (New)
function requestMHTMLCapture2(tabId) {
chrome.runtime.sendMessage({ action: 'captureMHTMLAndPNG', tabId: tabId });
}
// Request the active tab ID from the background script
function getActiveTabId(callback) {
chrome.runtime.sendMessage({ action: 'getTabId' }, function(response) {
if (response && response.tabId) {
callback(response.tabId);
} else {
console.error('Unable to get the active tab ID');
}
});
}
background.js relevant code:
chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
if (request.action === 'captureMHTMLAndPNG') {
const tabId = request.tabId;
// Make the function async to handle async calls in service workers
const captureContent = async () => {
try {
// Capture MHTML asynchronously
const mhtmlData = await new Promise((resolve, reject) => {
chrome.pageCapture.saveAsMHTML({ tabId: tabId }, resolve);
});
const reader = new FileReader();
reader.onloadend = async function () {
const mhtmlBase64 = reader.result.split(',')[1];
// Capture the current tab as a PNG
const dataUrl = await new Promise((resolve, reject) => {
chrome.tabs.captureVisibleTab(null, { format: 'png' }, resolve);
});
const pngBase64 = dataUrl.split(',')[1];
// Create a new instance of JSZip and add files
const zip = new JSZip();
zip.file(`page_${Date.now()}.mhtml`, mhtmlBase64, {
base64: true,
compression: "DEFLATE",
compressionOptions: { level: 9 }
});
zip.file(`screenshot_${Date.now()}.png`, pngBase64, {
base64: true,
compression: "DEFLATE",
compressionOptions: { level: 9 }
});
// Generate the ZIP file as a Blob
const blob = await zip.generateAsync({ type: "blob" });
const zipReader = new FileReader();
zipReader.onloadend = async function () {
const zipBase64 = zipReader.result.split(',')[1];
// Retrieve activeSessionToken and loggedUser asynchronously
const { activeSessionToken, loggedUser } = await chrome.storage.local.get(['activeSessionToken', 'loggedUser']);
if (activeSessionToken && loggedUser) {
const tab = await chrome.tabs.get(tabId);
let strippedUrl = new URL(tab.url);
strippedUrl = strippedUrl.origin + strippedUrl.pathname;
// Function to perform the fetch with retry logic
const fetchWithRetry = async (retries = 3) => {
try {
const response = await fetch('http://my-domain-here.com/script.php', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
filename: `page_${activeSessionToken}.zip`,
data: zipBase64,
user_id: loggedUser,
session_token: activeSessionToken,
url: strippedUrl
})
});
const data = await response.text();
console.log('Zipped MHTML and PNG sent to server:', data);
if (data === '0') {
console.log('Triggering modal dialog due to response');
chrome.tabs.sendMessage(tabId, { action: 'showWarningModal' });
} else if (data === '1') {
console.log('Server response indicates success:', data);
} else {
console.log('Unexpected server response:', data);
}
} catch (error) {
console.error('Error sending zipped MHTML and PNG:', error);
if (retries > 0) {
console.log(`Retrying... (${3 - retries} attempts left)`);
setTimeout(() => fetchWithRetry(retries - 1), 2000);
}
}
};
await fetchWithRetry(); // Call the fetch with retry logic
} else {
console.error('No active session token found.');
}
};
zipReader.readAsDataURL(blob);
};
reader.readAsDataURL(mhtmlData);
} catch (error) {
console.error('Error capturing content:', error);
}
};
captureContent(); // Call the async function
}
else if (request.action === 'getTabId') {
const getActiveTabId = async () => {
try {
const tabs = await new Promise((resolve, reject) => {
chrome.tabs.query({ active: true, currentWindow: true }, resolve);
});
if (tabs.length > 0) {
sendResponse({ tabId: tabs[0].id });
} else {
sendResponse({ tabId: null });
}
} catch (error) {
console.error('Error querying tabs:', error);
sendResponse({ tabId: null }); // Return null in case of error
}
};
getActiveTabId(); // Call the async function
return true; // Indicate that the response will be sent asynchronously
}
}
I can’t seem to wrap my brain around it – the permissions are clearly defined, and yet it keeps requesting them, and the entire process of PNG capture and MHTML capture fails, and nothing is zipped and sent to my remote script.
Why is this happening?