
1. 使用`chrome-remote-interface`库:
首先,确保已经安装了`chrome-remote-interface`库。如果没有安装,可以通过以下命令安装:
bash
npm install --save chrome-remote-interface
然后,在需要下载文件的页面上添加以下代码:
const remote = require('chrome-remote-interface');
const downloadLink = document.querySelector('a[href^="https://"]');
if (downloadLink) {
remote.sendMessage(downloadLink, 'download', {
fileName: 'example.txt',
});
}
这段代码会找到所有以`https://`开头的链接,并发送一个`download`消息给Chrome远程接口,请求下载该链接指向的文件。
2. 使用`chrome.tabs` API:
在需要下载文件的页面上,监听`click`事件,并在点击事件处理函数中打开新标签页,并获取到当前标签页的引用。然后,通过`chrome.tabs.executeScript()`方法执行JavaScript代码,下载文件。
javascript
document.addEventListener('click', function (event) {
const tabId = event.target.id;
const tab = chrome.tabs.get(tabId);
const downloadLink = tab.url;
// 下载文件
chrome.tabs.executeScript({
code: `window.open('${downloadLink}')`,
}, function () {
// 下载完成后的操作
});
});
注意:这种方法需要在支持`chrome.tabs.executeScript()`方法的环境中运行,例如Node.js或Electron。