[英]How do you capture a click as a user gesture?
我正在制作一個 Chrome 擴展程序,用於下載文件並將這些下載文件的鏈接添加到網頁。 單擊這些鏈接時,我想將單擊作為“用戶手勢”中繼到我的后台腳本,以便文件在沒有提示的情況下打開。 查看有關方法chrome.downloads.open的文檔,沒有討論用戶手勢。
使用此評論中的想法。
這似乎是可能的,因為
event
會產生一個 MouseEvent,類型click
和isTrusted
設置為 true。[downloads.open] 只能在由用戶操作發起的代碼中運行,例如單擊按鈕。 它不能從非用戶事件中執行。 - Xan, 評論如何打開下載的文件?
下面的代碼旨在成為 MCVE。
// Add an event listener for every download link
function addDownloadListeners() {
const pathElems = document.getElementsByClassName('pathClass');
for (path of pathElems) {
path.addEventListener('click', openDownload);
}
}
// Send a message with the download ID to the background script
function openDownload(event) {
const selector = '#' + event.currentTarget.id;
const downloadId = parseInt($(selector).attr('download_id'));
chrome.runtime.sendMessage({
'downloadId': downloadId,
}, function(response) {
if (response !== undefined) {
resolve(response.response);
} else {
reject(new Error(response.response));
}
});
}
{
"background": {
"scripts": ["js/background.js"]
},
"content_scripts": [
{
"js": [
"js/content_script.js"
],
"matches": ["*://*.website.com/*/urlpath*"],
"run_at": "document_end"
}
],
"permissions": [
"downloads",
"downloads.open"
],
"manifest_version": 2,
}
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
try {
chrome.downloads.open(request.downloadId);
} catch (e) {
sendResponse({response: 'Error opening file with download id ' +
request.downloadId + ' getting error ' + e.toString()
});
}
}
)
如何在不創建額外提示的情況下點擊打開下載?
無法阻止/使用需要用戶同意的 chrome 方法提示的替代方法。 根據 Chromium Extension google group 中的討論,
chrome.downloads.open
)需要通過提示獲得用戶同意。 chrome.downloads.open
的當前行為大約是 2014 年。
特別感謝 @wOxxOm 和 Decklin Johnston 使這個答案成為可能。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.