我一直在开发a chrome扩展,如果我在控制台中手动调用方法,它可以完美地工作,但只会下载一个空文件或
function extractData() {
console.log('Extracting data...');
const elements = document.querySelectorAll('.sf-grid__main-table');
console.log('Elements:', elements);
const data = [];
// Add column headings to the first row of the data array
//data.push({ itemTitle: "itemTitle", sku_number: "SKU", itemPrice: "Price", notes: "Notes" });
data.push({ itemTitle: "itemTitle", sku_number: "SKU", itemPrice: "Price", notes: "Notes" });
elements.forEach(element => {
console.log('Processing element:', element);
const ellipsis = element.querySelector('.ellipsis');
const itemTitle = ellipsis.querySelector('strong').textContent;
console.log('itemTitle:', itemTitle);
const sku_number = ellipsis.textContent.trim().replace(itemTitle, '');
console.log('sku_number:', sku_number);
const itemPrice = element.querySelector('.sfl-tooltip-toggle').getAttribute('value');
console.log('itemPrice:', itemPrice);
// Check if the item price is over 10.00 and the SKU number begins with "AQ," "Y," or "BTLG"
let notes = "";
if (parseFloat(itemPrice) > 10.00 && ["AQ", "Y", "BTLG"].includes(sku_number.substring(0, 2))) {
notes = "potential multibuy";
}
data.push({ itemTitle, sku_number, itemPrice, notes });
});
// Convert the data array to CSV format
const csvContent = data.map(row => Object.values(row).join(',')).join('\n');
console.log('csvContent:', csvContent);
// Create a Blob object from the CSV content
const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8' });
// Create an object URL from the Blob object
const url = URL.createObjectURL(blob);
// Use the downloadFile function to download the file
downloadFile(url, 'data.csv');
}
function downloadFile(url, fileName) {
// Create an anchor element
const anchor = document.createElement('a');
anchor.style.display = 'none';
anchor.href = url;
anchor.download = fileName;
document.body.appendChild(anchor);
// Click the anchor element
anchor.click();
// Remove the anchor element
document.body.removeChild(anchor);
// Revoke the object URL
URL.revokeObjectURL(url);
}
// Add a listener for the "click" event of the browser action
chrome.browserAction.onClicked.addListener(extractData);
清单.json
{
"manifest_version": 2,
"name": "CSV Generator",
"description": "Extracts data from a table ",
"version": "1.0",
"permissions": [
"activeTab",
"downloads"
],
"background": {
"scripts": ["extract-data.js"]
},
"browser_action": {
"default_icon": "icon.png",
"default_title": "Extract Data"
}
}
我试过在dom中添加一个链接并点击它,也试过使用blob。不知何故,我在点击和extractData方法之间丢失了数据。想知道是否有一些我不知道的安全问题?
1条答案
按热度按时间7cwmlq891#
后台脚本不能直接解析页面数据,你必须把它放在内容脚本中,或者你可以把页面DOM传递给后台脚本(read more)。
这就是内容脚本的工作原理,