Screen sharing stopped event: Cannot set property 'session' of undefined

I want client share webcam and screen. I can now do it but the problem I can not catch stopping screen share. I throws the Cannot set property 'session' of undefined error. Here is my code:

function shareScreen() {
    OVS = new OpenVidu();
    sessionScreen = OVS.initSession();
    var nickName = $("#nickName").val();
    getToken((token) => {
        sessionScreen.connect(token, {
                clientData: nickName + "_screen"
            })
            .then(() => {

                var publisher = OVS.initPublisherAsync("", {
                    videoSource: "screen"
                }).then(publisher => {
                    publisher.stream.getMediaStream().getVideoTracks()[0].addEventListener('ended', () => {
                        console.log('User pressed the "Stop sharing" button');
                    });
                });
                sessionScreen.publish(publisher);

            })
            .catch(error => {
                console.warn('There was an error connecting to the session:', error.code, error.message);
            });
    });
}

Can you tell me whats wrong with this code? Thank you.

Can you point the source code line where you have the issue?

@micael.gallego,

The code line is:
sessionScreen.publish(publisher);

Actually I fixed it. I moved the line inside the then function of publisher and it works. But now, publisher.on('videoElementCreated', (event) => { event does not fire in the then function. I move the videoElementCreated event outside of then function, I get the following error:

There was an error connecting to the session: undefined publisher.on is not a function

I am not good at JS so I guess, I’M missing something here.

Try with this:

function shareScreen() {
    OVS = new OpenVidu();
    sessionScreen = OVS.initSession();
    var nickName = $("#nickName").val();
    getToken((token) => {
        sessionScreen.connect(token, {clientData: nickName + "_screen"}).then(() => {
			var publisher = OVS.initPublisher("", {videoSource: "screen"});

			publisher.once('accessAllowed', (event) => {
				publisher.stream.getMediaStream().getVideoTracks()[0].addEventListener('ended', () => {
					console.log('User pressed the "Stop sharing" button');
				});
				sessionScreen.publish(publisher);

			});

			publisher.once('accessDenied', (event) => {
				console.warn('ScreenShare: Access Denied');
			});

		}).catch((error => {
			console.warn('There was an error connecting to the session:', error.code, error.message);

		}));
	}
}