繁体   English   中英

如果立即打开新选项卡,则无法在单击时捕获屏幕截图 - chrome 扩展

[英]Can't capture screenshot on click, if a new tab opens immediately - chrome extension

我正在构建一个 chrome 扩展程序,该扩展程序在单击超链接时捕获屏幕截图(选项卡)。 如果在单击超链接或按钮时打开新选项卡,则不会捕获当前选项卡。

错误:

Unchecked runtime.lastError: Cannot access contents of url "". Extension manifest must request permission to access this host.

在这种情况下如何捕获当前选项卡(不是新选项卡)?

在下面的示例中,如果单击第一个链接, dataUrl (屏幕截图数据)将为 null。 新选项卡快速打开,当 function 在后台脚本中执行时,焦点位于新选项卡上(请参阅当前选项卡 ID)。

重现:

index.html

<a id="first" href="https://www.example.org" target="_blank">Open link in new tab</a> <br>
<a id="second" href="https://www.example.org">Open link in same tab</a>

manifest.json

...
  "content_scripts": [
    {
      "matches": ["<all_urls>"],
      "js": ["content.js"],
      "css": ["content.css"]
    }
  ],
  "host_permissions": ["<all_urls>","*://localhost:8080/*"],
  "permissions": [
    "activeTab",
    "tabs"
  ],
...

content.js

/////////////// Capture tab on mouse click ///////////////
document.addEventListener("click", (e) => {

  chrome.runtime.sendMessage({ msg: "capture"}, function (response) {

  });
  console.log("inside click eventListener");
}, true);

background.js

chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {

  chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
        console.log("Current tab id", tabs[0].id);
        console.log("Sender tab id", sender.tab.id);
      });

  chrome.tabs.captureVisibleTab(
    null,
    {
      format: "png",
      quality: 100,
    },
    function (dataUrl) {
      console.log(dataUrl);
    }
  );

  return true;
});

如果您需要更多详细信息,请告诉我。 提前致谢!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM