GithubHelp home page GithubHelp logo

muaz-khan / getscreenid Goto Github PK

View Code? Open in Web Editor NEW
63.0 8.0 29.0 29 KB

getScreenId | Capture Screen on Any Domain! This script is a hack used to support single chrome extension usage on any HTTPs domain.

Home Page: https://www.webrtc-experiment.com/getScreenId/

License: MIT License

HTML 57.10% JavaScript 42.90%
chrome-extension capture-screen getscreenid webrtc getusermedia

getscreenid's Introduction

getScreenId | Capture Screen on Any Domain!

getScreenStream(function(screenStream) {
    video.srcObject = screenStream;
});

function getScreenStream(callback) {
    if (navigator.getDisplayMedia) {
        navigator.getDisplayMedia({
            video: true
        }).then(screenStream => {
            callback(screenStream);
        });
    } else if (navigator.mediaDevices.getDisplayMedia) {
        navigator.mediaDevices.getDisplayMedia({
            video: true
        }).then(screenStream => {
            callback(screenStream);
        });
    } else {
        getScreenId(function(error, sourceId, screen_constraints) {
            navigator.mediaDevices.getUserMedia(screen_constraints).then(function(screenStream) {
                callback(screenStream);
            });
        });
    }
}

npm downloads

  1. Install this: https://chrome.google.com/webstore/detail/screen-capturing/ajhifddimkapgcifgcodmmfdlknahffk
  2. Now use below codes on any HTTPs domain.
  3. Remember, HTTPs is required.
  4. getScreenId gives you "MediaStream" object; you can share that object with other users using AppRTC demo, SimpleWebRTC or EasyRTC or PeerJs libraries, or any standalone peer-to-peer demo.
  5. In simple words, you have to use RTCPeerConnection API along with getScreenId to share screen with other users.
npm instll webrtc-screen-capturing

Hacking to use single chrome-extension on any domain!

<!--
* This script is a hack used to support single chrome extension usage on any domain.

* This script has issues, though.
* It uses "postMessage" mechanism which fails to work if someone is using it from inside an <iframe>.
* The only solution for such cases is, use WebSockets or external servers to pass "source-ids".
-->

You don't need to PUBLISH/deploy your own chrome-extension when using this script!

LocalHost server

node server.js

Nope open: https://localhost:9001/

How to use?

<script src="https://cdn.WebRTC-Experiment.com/getScreenId.js"></script>
<script src="https://webrtc.github.io/adapter/adapter-latest.js"></script>

<video controls autoplay playsinline></video>

getScreenId

This method allows you get chrome-media-source-id; which can be used to capture screens.

getScreenId(function (error, sourceId, screen_constraints) {
    // error    == null || 'permission-denied' || 'not-installed' || 'installed-disabled' || 'not-chrome'
    // sourceId == null || 'string' || 'firefox'

    if(navigator.userAgent.indexOf('Edge') !== -1 && (!!navigator.msSaveOrOpenBlob || !!navigator.msSaveBlob)) {
        navigator.getDisplayMedia(screen_constraints).then(stream => {
            document.querySelector('video').srcObject = stream;
        }, error => {
            alert('Please make sure to use Edge 17 or higher.');
        });
        return;
    }

    if(error == 'not-installed') {
      alert('Please install Chrome extension.');
      return;
    }

    navigator.mediaDevices.getUserMedia(screen_constraints).then(function (stream) {
        document.querySelector('video').srcObject = stream;

        // share this "MediaStream" object using RTCPeerConnection API
    }).catch(function (error) {
      console.error('getScreenId error', error);

      alert('Failed to capture your screen. Please check Chrome console logs for further information.');
    });
});

Or...

getScreenId(function (error, sourceId, screen_constraints) {
    // error    == null || 'permission-denied' || 'not-installed' || 'installed-disabled' || 'not-chrome'
    // sourceId == null || 'string' || 'firefox'

    if(sourceId && sourceId != 'firefox') {
        screen_constraints = {
            video: {
                mandatory: {
                    chromeMediaSource: 'screen',
                    maxWidth: 1920,
                    maxHeight: 1080,
                    minAspectRatio: 1.77
                }
            }
        };

        if (error === 'permission-denied') return alert('Permission is denied.');
        if (error === 'not-chrome') return alert('Please use chrome.');

        if (!error && sourceId) {
            screen_constraints.video.mandatory.chromeMediaSource = 'desktop';
            screen_constraints.video.mandatory.chromeMediaSourceId = sourceId;
        }
    }

    navigator.getUserMedia = navigator.mozGetUserMedia || navigator.webkitGetUserMedia;
    navigator.getUserMedia(screen_constraints, function (stream) {
        document.querySelector('video').src = URL.createObjectURL(stream);

        // share this "MediaStream" object using RTCPeerConnection API
    }, function (error) {
      console.error('getScreenId error', error);

      alert('Failed to capture your screen. Please check Chrome console logs for further information.');
    });
});

getChromeExtensionStatus

This method allows you detect whether chrome extension is installed or not:

getChromeExtensionStatus(function(status) {
    if (status === 'installed-enabled') alert('installed');
    if (status === 'installed-disabled') alert('installed but disabled');
    // etc.
});

How it works?

  • Your script will make a postMessage request to getScreenId.js
  • getScreenId.js will connect with chrome-extension using an internal <iframe>.
  • That <iframe> is loaded from domain: https://www.webrtc-experiment.com/
  • That <iframe> can connect with chrome-extension. It can send/receive postMessage data.
  • Same postMessage API are used to pass screen-id back to your script.

Custom Parameter

Pass second argument to getScrenId method:

  • true means that capture system audio i.e. speakers
  • [] array means that capture custom array items
getScreenId(successCallback, true);    // capture speakers
getScreenId(successCallback, ['tab']); // capature only tab
getScreenId(successCallback, ['window']); // capature only app's windows
getScreenId(successCallback, ['screen', 'audio']); // capature only screen with speakers

Firefox

Deploy extension yourself?

Alternative?

Disclaimer

There is no warranty, expressed or implied, associated with this product. Use at your own risk.

License

getScreenId.js is released under MIT licence . Copyright (c) Muaz Khan.

getscreenid's People

Contributors

muaz-khan avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

getscreenid's Issues

Chrome extension status is: installed-disabled

I'd like to host all the dependencies myself.
I modified getScreenId.js to embed getScreenId.html served from my own domain.
//iframe.src = 'https://www.webrtc-experiment.com/getSourceId/'; // https://wwww.yourdomain.com/getScreenId.html iframe.src = 'getScreenId.html'; // https://wwww.yourdomain.com/getScreenId.html

But when I click: Capture Your Own Screen in the example provided (index.html) I get the following message:
Chrome extension status is: installed-disabled

The full url is https://localhost:8080/getScreenId.html.
I tried that too but that didn't make a difference.

Adding microphone sound to screen sharing

when screen sharing Setting up audio:true is error

var screen_constraints = { audio:true, video: { mandatory: { chromeMediaSource: error ? 'screen' : 'desktop', maxWidth: window.screen.width > 1280 ? window.screen.width : 1280, maxHeight: window.screen.height > 720 ? window.screen.height : 720 }, optional: [] } };
is error
Can I collect the microphone, how do I do it, Thank you

Share with others

Thanks for tutorial. How can i share my screen with others?

Thank you!

Problem getting the screen after selecting the window- Screen Share

I'm trying to implement the screen share functionality in Firefox.
I've tried implementing the extension as you said but that didn't work. Then I came to know that I can do that without the extension.

I wrote your code which is in "capture-screen" onclick event.
But, I can select the window(as in your demo) but then I can not see the shared screen.

This is what I do in my JS file in onclick event:

`getScreenId(function(error, sourceId, screen_constraints) {

                    if (IsAndroidChrome) {
                        screen_constraints = {
                            mandatory: {
                                chromeMediaSource: 'screen'
                            },
                            optional: []
                        };
                        
                        screen_constraints = {
                            video: screen_constraints
                        };

                        error = null;
                    }

                    if(error == 'not-installed') {
                      alert('Please install Chrome extension. See the link below.');
                      return;
                    }

                    if(error == 'installed-disabled') {
                      alert('Please install or enable Chrome extension. Please check "chrome://extensions" page.');
                      return;
                    }

                    if(error == 'permission-denied') {
                      alert('Please make sure you are using HTTPs. Because HTTPs is required.');
                      return;
                    }

                    console.info('getScreenId callback \n(error, sourceId, screen_constraints) =>\n', error, sourceId, screen_constraints);

                    navigator.getUserMedia = navigator.mozGetUserMedia || navigator.webkitGetUserMedia;
                    navigator.getUserMedia(screen_constraints, function(stream) {

                        document.querySelector('video').src = URL.createObjectURL(stream);

                        stream.oninactive = stream.onended = function() {
                            document.querySelector('video').src = null;
                        };

                    }, function(error) {
                        console.error('getScreenId error', error);

                        alert('Failed to capture your screen. Please check Chrome console logs for further information.');
                    });
                });`

I have also getScreenId.js as you stated.

Kindly tell me what I'm doing wrong.

Thank you.

getChromeExtensionStatus() does not follow the standard NodeJS conventions

According to NodeJS conventions, the callback should be error-first, meaning getChromeExtensionStatus() should return a callback with an error as the first value and the status as the second value.

I am using Bluebird's promisify function with getChromeExtensionStatus() and I have to use .catch because of that.

Promise.promisify(window.getChromeExtensionStatus)()
  .catch(function(error) {
    console.log(error.message) // will get me the status
});

here is my suggestion

window.getChromeExtensionStatus = function(callback) {
    // for Firefox:
    if (!!navigator.mozGetUserMedia) {
      callback(new Error('not-chrome'), null);
      return;
    }

    window.addEventListener('message', onIFrameCallback);

    function onIFrameCallback(event) {
      if (!event.data) return;

      if (event.data.chromeExtensionStatus) {
        if (event.data.chromeExtensionStatus === 'installed-enabled') {
          callback(null, event.data.chromeExtensionStatus);
        } else {
          callback(new Error(event.data.chromeExtensionStatus), null);
        }
      }

      // this event listener is no more needed
      window.removeEventListener('message', onIFrameCallback);
    }

    setTimeout(postGetChromeExtensionStatusMessage, 100);
  };

getScreenId needs to be called twice to work

hello,

I tried to use getScreenId in my own application but it needs to be called twice to work. After investigation, I found the culprit, https://github.com/muaz-khan/getScreenId/blob/master/getScreenId.js#L55. The listener on the message is removed a bit too soon.

During the first call, the value of event.data is

{request: "postUri", uri: "https://www.webrtc-experiment.com/getSourceId/"}

Based on the logic, it will remove the listener before triggering the correct value back to my custom code.

During the second call, the value of event.data is

{chromeMediaSourceId: "xhtC84z5dQzNWCZIFq5owA=="}

If found out that the code works fine in your example (https://github.com/muaz-khan/getScreenId/blob/master/index.html) because you are calling the method getChromeExtensionStatus which will simulate the first call.

Shouldn't we only remove the listener when calling the callback in getScreenId ?

i.e

window.getScreenId = function(callback) {
        // for Firefox:
        // sourceId == 'firefox'
        // screen_constraints = {...}
        if (!!navigator.mozGetUserMedia) {
            callback(null, 'firefox', {
                video: {
                    mozMediaSource: 'window',
                    mediaSource: 'window'
                }
            });
            return;
        }

        window.addEventListener('message', onIFrameCallback);

        function onIFrameCallback(event) {
            if (!event.data) return;

            if (event.data.chromeMediaSourceId) {
                // this event listener is no more needed
                window.removeEventListener('message', onIFrameCallback);
                if (event.data.chromeMediaSourceId === 'PermissionDeniedError') {
                    callback('permission-denied');
                } else callback(null, event.data.chromeMediaSourceId, getScreenConstraints(null, event.data.chromeMediaSourceId));
            }

            if (event.data.chromeExtensionStatus) {
                // this event listener is no more needed
                window.removeEventListener('message', onIFrameCallback);
                callback(event.data.chromeExtensionStatus, null, getScreenConstraints(event.data.chromeExtensionStatus));
                
            }

            // this event listener is no more needed
            //window.removeEventListener('message', onIFrameCallback);
        }

        setTimeout(postGetSourceIdMessage, 100);
    };

Best regards

Screen Sharing With Audio

hi, I want to share the screen with audio. Firefox is ok, but chrome is not.
the callback paramter of constraints in chrome is following:
screen_constraints { "video": { "mandatory": { "chromeMediaSource": "desktop", "maxWidth": 1280, "maxHeight": 720, "chromeMediaSourceId": "duqJhQS6UlzRqFpgGB4W5w==", "maxFrameRate": 10 }, "optional": [] }, "audio": true }
in firefox is following:
screen_constraints { "video": { "mozMediaSource": "screen", "mediaSource": "screen", "width": { "max": 1280 }, "height": { "max": 720 }, "frameRate": { "max": 10 } }, "audio": true }

after function getUserMedia(), it will be going to the failed callback, the error message is none as following:
NavigatorUserMediaError {name: "ScreenCaptureError", message: "", constraintName: ""}

How can I do if I want to share screen with audio in chrome?

Thanks!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.