LoginSignup
3
2

More than 5 years have passed since last update.

Chromeアプリ:screen shareを作りたい(DesktopCapture編)

Last updated at Posted at 2015-01-29

chromeアプリのscreen shareでよく使われるDesktopCaptureについてメモメモ

とりあえず既にあるものを見てみる。

chrome extensions samples の desktopcaptureからファイルを取得
Sample Extensions   Google Chrome.png

前回の記事と同じようにchromeの拡張機能に読み込ませて実行すれば使える。

chromeアプリ:アイコンをクリックしたら表示されるアプリ

今日のテーマ:アイコンから実行できるように改良する

1.アイコンから実行できるようにmanifest.jsonに
browser_actionを追加する。またbackgroundも変更する。

manifest.json
{
  "name": "sample app",
  "description": "sample app",
  "version": "0.1",
  "manifest_version": 2,
  "icons": {
    "16": "icon.png",
    "128": "icon.png"
  },
    "background": {
      "scripts": ["background.js"]
  },
  "permissions": [
    "desktopCapture"
  ],
  "browser_action": {
  }
}



2.アイコンがクリックされたら実行される命令をbackground.jsに書く。

background.js
chrome.browserAction.onClicked.addListener(function(){
    chrome.windows.create({
        url: "index.html",
        focused: true,
        type: "popup"
    });
});

クリックされた時,index.htmlに基づいてページが作られる。


3.index.htmlを作る
startボタンを押せば,共有画面選択ページが開き,選択するとhtmlに共有画面が出力されるものを作る。
つまりhtmlではstartボタンとvideoがあればよいので以下のようになる。

index.html
<video id="video" autoplay></video>

<button id="start">Start</button>
<script src="app.js"></script>

ただし,app.jsはstartボタンを押した時のイベントコードが記述されるjsファイルである。


4.app.jsを作る
startボタンをクリックしたら発動する命令は

document.getElementById("start").addEventListener("click", function(e){///}

となる。また共有画面選択ページを表示する命令は

chrome.desktopCapture.chooseDesktopMedia(
        ["screen", "window"], function(streamId) {///選択した画面のIdをstreamIdとして取得している///},エラーのときに実行される関数)

となる。このstreamIdをつかってvideoに情報を渡す。

navigator.webkitGetUserMedia(
{音声:なし,画像:streamIdの情報},
function(stream){id="video"のsrcにstreamで作ったURLをわたす},
エラーのときに実行される);

このときstreamは{音声:なし,画像:streamIdの情報}からの情報を受け取っている。

まとめると

app.js
document.getElementById("start").addEventListener("click", function(e){
    chrome.desktopCapture.chooseDesktopMedia(
        ["screen", "window"], function(streamId) {
            navigator.webkitGetUserMedia(
                {
                    audio: false,
                    video: { mandatory: {
                        chromeMediaSource: "desktop",
                        chromeMediaSourceId: streamId
                        }
                    }
                },
                function(stream){
                    document.getElementById("video").src = URL.createObjectURL(stream);
                },
                function(){alert("error")}
            );  
        }
    );
});

となる。

スクリーンショット 2015-01-30 07.40.58.png

3
2
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2