我正在尝试将spotify身份验证添加到单页面应用程序中。
这是我的按钮点击处理程序事件。
var CLIENT_ID = '****';
var REDIRECT_URI = window.location.href;
function getLoginURL(scopes) {
return 'https://accounts.spotify.com/authorize?client_id=' + CLIENT_ID +
'&redirect_uri=' + encodeURIComponent(REDIRECT_URI) +
'&scope=' + encodeURIComponent(scopes.join(' ')) +
'&response_type=token';
}
var url = getLoginURL([
'user-read-email',
'user-read-birthdate',
'user-read-private',
'user-library-modify',
'user-library-read',
'user-follow-read',
'user-follow-modify',
'streaming',
'playlist-modify-private',
'playlist-modify-public',
'playlist-read-collaborative',
'playlist-read-private'
]);
var width = 450,
height = 730,
left = (window.screen.width / 2) - (width / 2),
top = (window.screen.height / 2) - (height / 2);
window.open(url,
'Spotify',
'menubar=no,location=no,resizable=no,scrollbars=no,status=no, width=' + width + ', height=' + height + ', top=' + top + ', left=' + left
);
console.log("window is open");
});
执行身份验证时,应该使用window.addEventListener('message')
这是事件监听器:
componentDidMount() {
window.addEventListener('message', (event) => {
***console.log("Spotify Window sent event data.");
var hash = JSON.parse(event.data);
if (hash.type == 'access_token') {
console.log(hash.access_token);
}
}); }
但它不起作用。这里的问题在哪里?标有***的部分甚至不起作用。
顺便说一句,我使用了这个文档:http://jsfiddle.net/JMPerez/62wafrm7/
答案 0 :(得分:1)
由于Spotify会重定向回您的页面,因此可能会在安装组件之前触发事件,这意味着窗口不会监听它。
我会考虑将您的window.addEventListener()
代码移到任何组件之外的index.js文件中。