Chrome 扩展:捕获桌面时,选中的 Window 聚焦在前面

Chrome Extension : While Capturing Desktop, selected Window is focused in front

伙计们,我有一个 chrome 扩展程序,它使用 chrome.desktopCapturenavigator.webkitGetUserMediacanvas 捕获 selected 桌面 window 的图像.当我要求用户 select window 进行分享时,selected window 会聚焦到前面。

这是我的代码 -

manifest.json -

{
  "name": "Desktop Capture Example",
  "description": "Show desktop media picker UI",
  "version": "1",
  "manifest_version": 2,
  "background": {
     "persistent": false,
      "scripts": ["background.js"]
  },
    "browser_action": {
    "default_title": "Take a screen shot of Desktop!"
  },
  "permissions": [
    "desktopCapture"
  ]
}

background.js -

var pending_request_id = null;

chrome.browserAction.onClicked.addListener(function() {

   pending_request_id = chrome.desktopCapture.chooseDesktopMedia(["screen", "window"],onAccessApproved);

});

function gotStream(stream) {
  console.log("Received local stream");
  var video = document.createElement('video');
  video.addEventListener('loadedmetadata',function(){
      var canvas = document.createElement('canvas');
      canvas.width = this.videoWidth;
      canvas.height = this.videoHeight;
      var ctx = canvas.getContext("2d");
      ctx.drawImage(this, 0, 0);
      var url = canvas.toDataURL();
      console.log(url);
      // will open the captured image in a new tab
      //window.open(url);
    },false);
  video.src = URL.createObjectURL(stream);
  video.play();
  }

function getUserMediaError() {
  console.log("getUserMedia() failed.");
}

function onAccessApproved(id) {
  if (!id) {
    console.log("Access rejected.");
    return;
  }
  navigator.webkitGetUserMedia({
      audio:false,
      video: { mandatory: { chromeMediaSource: "desktop",
                            chromeMediaSourceId: id,
                            maxWidth: 4000,
                            maxHeight: 4000} }
  }, gotStream, getUserMediaError);
}

但是,如果我使用 window.open(url),焦点将设置到打开的 window 而不是共享的 window。但是,如果我使用 chrome.tabs.create({url: url,active : true},function(tab){}) 打开 url,而不是使用 window.open,共享 window 会聚焦在打开的顶部 tab.I 希望打开的选项卡不聚焦分享 window.How 给我做这个?

您需要使用 chrome.tabs api 通过更新方法切换活动标签:https://developer.chrome.com/extensions/tabs#method-update

在 Chrome33 之前,您会这样做:

chrome.tabs.update(tabId, {selected: true});

我相信这已更改为:

chrome.tabs.update(tabId, {active: true});

根据选项卡的对齐方式,您可能还需要 chrome.windows api: chrome.windows.update,查看 focused 参数(也在 chrome.tabs api 文档)。

编辑:设置错误 属性,已更正。

除了 Brian 的回答之外,您还希望在创建了一个在 window 中处于活动状态的选项卡后使 window 成为焦点。

这是类似的做法:

chrome.tabs.create({url: url, active: true}, function(tab) {
  chrome.windows.update(tab.windowId, {focused: true});
});