chrome.pageCapture.saveAsMHTML and chrome.tabs.captureVisibleTab not working properly in Manifest v3 – RESOLVED

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?

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật