簡體   English   中英

如何將點擊捕獲為用戶手勢?

[英]How do you capture a click as a user gesture?

問題

我正在制作一個 Chrome 擴展程序,用於下載文件並將這些下載文件的鏈接添加到網頁。 單擊這些鏈接時,我想將單擊作為“用戶手勢”中繼到我的后台腳本,以便文件在沒有提示的情況下打開。 查看有關方法chrome.downloads.open的文檔,沒有討論用戶手勢。

本質上,我想擺脫這個=> 提示我想搶占

使用此評論中的想法。

背景

這似乎是可能的,因為

  • 這篇關於什么構成用戶手勢的帖子將點擊列為用戶手勢的一種類型
  • 規范說點擊會產生用戶手勢
  • 在下面的代碼中,記錄event會產生一個 MouseEvent,類型clickisTrusted設置為 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));
    }
  });
}

manifest.json

{
  "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 方法(如chrome.downloads.open )需要通過提示獲得用戶同意。
  • 這些是通過 Chrome 本身自動生成的 - 它們不能被覆蓋或修改。
  • 提示之外的用戶手勢與需要用戶同意的方法無關。

chrome.downloads.open的當前行為大約是 2014 年

特別感謝 @wOxxOm 和 Decklin Johnston 使這個答案成為可能。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM