player.setChannel not working (Embed Twitch)

<script src= "http://player.twitch.tv/js/embed/v1.js"></script>
<div id="embed"></div>
<script type="text/javascript">
var options = {
	width: 854,
	height: 480,
	channel: "",
};

var player = new Twitch.Player("embed", options);
var newChannel = "dj_expo"
player.setChannel(newChannel);
</script>

Hello, I’m trying to create an iframe with code, and then change the channel (that is empty by default), but the “player.setChannel” doesn’t work. And in the console, no error appears.

Thank you

I switched

<script src= “http://player.twitch.tv/js/embed/v1.js”></script>

for

<script src= “https://player.twitch.tv/js/embed/v1.js”></script>

And the code you pasted works

https://twitch.extensions.barrycarlyon.co.uk/temp/test_24323.html

(My test site is over https and won’t load http content for security reasons)

Hi, thanks for the reply. Sorry for my bad english :sweat_smile:

That code was just a test, and it had a mistake the http. The real problem is, as I said, the player.setChannel. I’m doing a script that updates the channel that is in the iframe, and I have a variable called actualChannel with value of = onlineUsers.data[0].user_name.

Then I show it in the console with console.log(actualChannel); and this works fine, but when in the code player.setChannel(actualChannel), the iframe keeps black and doesn’t do nothing, in console no error appears. It’s like the variable is null but no, because in the console appears the channel without any problem.

Thank you for reading :smile:

Present your full code then.

Not just the snippet that works fine when I copy/paste it to my html file

"use strict";

const callAJAX = (props) => {
    const url = props.url,
          method = props.method || "GET",
          type = props.type || "JSON",
          header = props.header
    ;
    
    return new Promise(waitForResult => {
        const xhttp = new XMLHttpRequest();
        xhttp.onreadystatechange = function() {
            if (this.readyState === 4 && this.status === 200) {
                type === "text" 
                    ? waitForResult(this.response)
                    : waitForResult(JSON.parse(this.response))
                ;
            }
        };
        if (method === "GET") {
            xhttp.open("GET", url, true);
            for (const key in props.header) {
                xhttp.setRequestHeader(key, header[key]);
            }
            xhttp.send();
        }
    });
};

const AJAXProps = {
    url: "https://api.twitch.tv/helix/streams?first=20",
    header: {"client-ID": "2qyh8p71ip7wb5duz7s7j4ctujehqn"} //Api key
};

//Array of users (channels)
var users = ["helanyah", "exbc", "rajobostv", "zorro", "esl_sc2"];

let names = "";
for (let i = 0;  i < users.length; i++) {
    let name = users[i];
    !(names) 
        ? names += name
        : names += `&login=${name}`
    ;
};

// Create Twitch iframe

	var actualStream = "";

	// Embed stream
	var options = {
    width: 1280,
    height: 720,
	channel: actualStream
	};
	
	var player = new Twitch.Player("twitchEmbed", options);
	document.getElementsByTagName("iframe")[0].setAttribute("sandbox", "allow-scripts allow-top-navigation allow-same-origin");
	
// Get users:

function updateStreams() {
	AJAXProps.url = `https://api.twitch.tv/helix/users?login=${names}`;
	callAJAX(AJAXProps).then(allUser => {
		AJAXProps.url = `https://api.twitch.tv/helix/streams?first=20&login=${names}`.replace(/login/g, "user_login"); // Check if users now streaming
		// The names inconsistent, so have to work with user_id
		users.forEach((user, i) => {
			users[i] = allUser.data[i].id;
		});
		callAJAX(AJAXProps).then(onlineUsers => {
			console.log("Check if the given users now streaming", onlineUsers);
			var numberOnline = onlineUsers.data.length;
		
		if (numberOnline > 0) {
			var actualStream = onlineUsers.data[0].user_name;
		}
		
		player.setChannel(actualStream);
		
		});
	});
} setInterval(updateStreams, 6000);
updateStreams();
		if (numberOnline > 0) {
			var actualStream = onlineUsers.data[0].user_name;
		}
		
		player.setChannel(actualStream);

is wrong

I also made a couple of other fixes

https://twitch.extensions.barrycarlyon.co.uk/temp/test_24323_b.html

Notably how the URL’s are constructed (using a join instead of a string replace)

Your setInterval was also variable trashing… For some reason you were extracting the users ID’s and overwriting the users name array to be user_id’s instead breaking follow up calls. So I commented that section out. Not sure your intent there. You swap the names out for ID’s and then it’s all broken. Either start with ID’s or names, don’t convert mid way thru the life of the program

You also do nothing to stop the channel changing if the channel is the same and/or if more than one channel is live. It’ll change channel 5 times every 6 seconds if all 5 channels are live.

Consider something like

            var live = [];
            if (numberOnline > 0) {
                live.push(onlineUsers.data[0].user_name);
            }

            if (live[0]) {
                player.setChannel(live[0]);
            }

Hello, the code that I uploaded last week now is working. But if it is possible, I would like the player not to be updated when the channel that is being displayed is the same, and then, updated when a new channel is placed in the “live” array above it. Thank you

Then add basic javascript to prevent this…

Something like

            if (numberOnline > 0) {
                actualStream = onlineUsers.data[0].user_name;
                if (actualStream  != lastStream) {
                    player.setChannel(actualStream);
                    lastStream = actualStream;
                }
            }

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.