muaz-khan / getScreenId

getScreenId | Capture Screen on Any Domain! This script is a hack used to support single chrome extension usage on any HTTPs domain.
https://www.webrtc-experiment.com/getScreenId/
MIT License
63 stars 29 forks source link

getScreenId needs to be called twice to work #4

Closed prbaron closed 6 years ago

prbaron commented 6 years ago

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