此方法上传文件需要模拟手动点击网页文件框,对prompt、alert、confirm这三种弹窗有效。
注意:
1,在自动上传文件时,同一个tab页中可以跨框架(iframe)。
2,因为本质是模拟点击上传文件,所以点击时需要tab页处于激活状态且选择的css选择器元素可以被点击或可以被设为焦点,如按钮元素,input元素。
window.aa和window.bb这两个全局变量是用来充当中间变量的,因为没有想到更好的解决方式。
现MV3版浏览器插件,由于没有找到可以直接添加监视器函数和加载监视器的方法,没有想到解决方案。
以下是mv2版的子程序可以测试:
https://getquicker.net/subprogram?id=5f32c3a6-6cbb-441e-b349-08dd9e2f4cec
//监视器函数
function handleDebuggerEvent(source, method, params) {
if (method === "Page.javascriptDialogOpening") {
chrome.debugger.sendCommand(source, "Page.handleJavaScriptDialog",{"accept": window.aa})
};
if (method === 'Page.fileChooserOpened') {
chrome.debugger.sendCommand(source, "DOM.setFileInputFiles", {"backendNodeId":params.backendNodeId,"files":window.bb})
};
}
function 加载监控器(tabId){
chrome.debugger.sendCommand({ tabId: tabId }, 'Page.enable');
chrome.debugger.sendCommand({ tabId: tabId }, 'Page.setInterceptFileChooserDialog', { enabled: true });
chrome.debugger.onEvent.addListener(handleDebuggerEvent);
console.log("已加载监控器");
}
function 删除监控器(tabId){
chrome.debugger.sendCommand({ tabId: tabId }, 'Page.setInterceptFileChooserDialog', { enabled: false });
chrome.debugger.onEvent.removeListener(handleDebuggerEvent);
window.aa=null;window.bb=null;
console.log("已删除监控器");
}
function 连接(tabId){
chrome.debugger.attach({ tabId: tabId }, '1.3');
加载监控器(tabId);
};
function 断开(tabId){
chrome.debugger.detach({ tabId: tabId })
console.log("断开连接");
};