我的manifest.json檔案:
{
"manifest_version": 3,
"name": "上傳類型提醒",
"version": "1.0",
"permissions": ["activeTab","webRequest","declarativeNetRequest"],
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["background.js"]
}
]
}
我的background.js檔案:
document.addEventListener('change', function(event) {
const input = event.target;
if (input.type === 'file') {
const files = input.files;
for (let i = 0; i < files.length; i++) {
const fileName = files[i].name.toLowerCase();
if (fileName.endsWith('.bmp') || fileName.endsWith('.png') || fileName.endsWith('.gif') || fileName.endsWith('.doc') || fileName.endsWith('.docx') || fileName.endsWith('.xls') || fileName.endsWith('.xlsx')) {
alert('此檔案類型不允許上傳:' + files[i].name);
input.value = ''; // 清空文件輸入
break;
}
}
}
});
我用Chrome瀏覽器擴充功能,點選載入未封裝項目
來載入這兩個程式碼
但真正上傳檔案時
只會跳出視窗「此檔案類型不允許上傳」提醒
然後就繼續上傳那個檔案
所以我想改成
同樣跳出視窗「此檔案類型不允許上傳」的提醒
然後過三秒後直接關掉目前瀏覽的網頁
或是整個Chrome瀏覽器的關掉也可以
我該如何改變我的代碼
intput 的 type 為 file 型態
此句無效
input.value = ''; // 清空文件輸入
你應該是要重新置換html元素才行吧~
例如這樣~
HTML
<span id="UploadDp"><input type="file" id="UploadFile" name="UploadFile"></span>
JS
UploadDp.innerHTML = "<input type=\"file\" id=\"UploadFile\" name=\"UploadFile\">";
瀏覽器關掉的程式碼 (但是通常會跳出提醒訪客,瀏覽器是否關閉的詢問)
window.close();
content.js
這段程式碼會攔截 的選擇,並在偵測到被封鎖的檔案後:
document.addEventListener("change", function (event) {
if (event.target.tagName.toLowerCase() === "input" && event.target.type === "file") {
const forbiddenExtensions = [".bmp", ".png"];
const files = event.target.files;
let hasForbiddenFile = false;
for (let file of files) {
let ext = file.name.slice(file.name.lastIndexOf(".")).toLowerCase();
if (forbiddenExtensions.includes(ext)) {
hasForbiddenFile = true;
break;
}
}
if (hasForbiddenFile) {
alert("禁止上傳該類型的檔案!3 秒後關閉網頁!");
event.target.value = ""; // 清空選取的檔案
setTimeout(() => {
window.close(); // 關閉當前網頁
}, 3000);
}
}
});
可以試試
建議換個思路,只允許特定類型檔案。
加上 accept
指定只接收的類型。不就可以阻擋選取非預期檔案了嗎?
<input type="file" id="avatar" name="avatar" accept="image/png, image/jpeg" />
我沒寫過 Chrome 擴充。不過一般 javascript 邏輯如下
document.querySelectorAll("input[type=file]").forEach(el=>{el.setAttribute('accept', 'text/plain')})
將 text/plain
換成需要接受的MIME