Как предотвратить загрузку Chrome при перехвате через сценарий контента в Manifest V3?Javascript

Форум по Javascript
Ответить
Anonymous
 Как предотвратить загрузку Chrome при перехвате через сценарий контента в Manifest V3?

Сообщение Anonymous »

Я строю расширение Chrome (Manifest v3), которое перехватывает ссылки на загрузку файлов (например, .zip, .exe, .mp4 и т. Д.) На страницах, таких как благодарность или страницы успеха, и перенаправляет их в мое рабочее приложение (выбираю) вместо того, чтобы загрузить их напрямую. Несмотря на то, что я звоню e.preventdefault () и e.stoppropagation () в моем сценарии контента.
моя цель :
rentcept download and:
1. /> 2. Отправить URL-адрес файла в мое локальное приложение через http post
что работает :
-> Скрипт содержимого. (http: // localhost: 12345/api/download).
то, что не работает :
-> chrome до сих пор загружает файл навигающим, даже после перехвата. />

Код: Выделить всё

{
"manifest_version": 3,
"name": "Fetchify Downloader",
"version": "1.0",
"description": "Send downloads directly to the Fetchify app from your browser.",
"background": {
"service_worker": "background.js"
},
"permissions": [
"downloads",
"contextMenus",
"activeTab",
"scripting"
],
"content_scripts": [
{
"matches": [""],
"js": ["autoDownloadScript.js"],
"run_at": "document_idle"
}
],
"host_permissions": [""],
"icons": {
"16": "icons/icon16.png",
"32": "icons/icon32.png",
"48": "icons/icon48.png",
"128": "icons/icon128.png"
}
}
my autodownloadscript.js :

Код: Выделить всё

(function () {
const downloadExtensions = /\.(zip|exe|mp4|mp3|pdf|iso|rar|7z|msi|deb|apk|tar\.gz|docx?|xlsx?|pptx?)$/i;

function sendToFetchify(url) {
console.log("[Fetchify] Auto-detected download:", url);

fetch("http://localhost:12345/api/download", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ url })
})
.then(res => {
if (res.ok) console.log("✅ Sent to Fetchify.");
else console.warn("⚠️ Rejected by Fetchify.");
})
.catch(err => console.error("❌ Fetchify error:", err));
}

function interceptLinkClick(e) {
const anchor = e.target.closest("a");
if (!anchor || !anchor.href) return;

const url = anchor.href;

if (downloadExtensions.test(url)) {
e.preventDefault(); // Stop Chrome default download
e.stopPropagation();

console.log("[Fetchify] Intercepted link click:", url);
sendToFetchify(url);
}
}

function preventDefaultOnMatchingLinks() {
const links = document.querySelectorAll("a[href]");
for (const link of links) {
if (downloadExtensions.test(link.href)) {
link.addEventListener("click", e => {
e.preventDefault();
e.stopPropagation();
sendToFetchify(link.href);
});
}
}
}

function tryAutoDetectDownloadLinks() {
const links = Array.from(document.querySelectorAll("a[href]"));
for (const a of links) {
if (downloadExtensions.test(a.href)) {
console.log("[Fetchify] Auto-detected static link:", a.href);
sendToFetchify(a.href);
break; // Only handle one
}
}
}

// Intercept user clicks early (for dynamic DOM)
document.addEventListener("click", interceptLinkClick, true);

// Prevent static links from triggering download
window.addEventListener("DOMContentLoaded", preventDefaultOnMatchingLinks);

// Auto-detect on thank-you/success pages
window.addEventListener("load", () => {
const url = window.location.href.toLowerCase();
if (url.includes("thank-you") || url.includes("success")) {
setTimeout(tryAutoDetectDownloadLinks, 1500);
}
});
})();
Что я попробовал :
-> с использованием e.preventdefault () и e.stoppropagation () как в фазах захвата, так и в пузырях. /> -> Сопоставление и работает на документе_идле.
Вопросы:
1. Есть ли надежный способ предотвращения загрузки файла. (например, фоновый скрипт или с Chrome.webrequest )?
3.>

Подробнее здесь: https://stackoverflow.com/questions/796 ... ontent-scr
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Javascript»