我正在构建一个网络工具,它应该能够调用 Strava api。在能够创建实际请求之前,客户应给予授权。这是通过授权调用完成的: https://www.strava.com/oauth/authorize?client_id=123456&response_type=code&redirect_uri=http://localhost/exchange_token&approval_prompt=force&scope=activity:read_all
它由链接到我的应用程序的
client_id
和重定向 URL 组成。打开 URL 时,用户会看到一个屏幕,他/她可以在其中授权我的应用程序。批准后,他/她被重定向到带有名为 code=730f5fbb0b7djske9d66e85568a526e4e8sfb2ah
的查询参数的重定向 URL。这是进行新呼叫时应使用的实际授权代码。
我的问题是如何:
code
查询参数进行新调用
const url = await 'https://www.strava.com/oauth/authorize?client_id=123456&response_type=code&redirect_uri=http://localhost/exchange_token&approval_prompt=force&scope=activity:read_all';
const authPopup = window.open(url, "", "popup=true");
第 2 步应该由客户完成,但是有人可以帮助我完成第 3 步和第 4 步吗?欢迎任何提示。我对 JavaScript 还很陌生。
postMessage
和
onmessage
全局方法与打开的窗口进行通信。
onmessage
意味着打开弹出窗口的脚本通过
postMessage
接收弹出窗口发送的数据。
window.onmessage = ({ data }) => { // data is sent from the popup
if(data?.type === 'close'){
window.auth_popup?.close(); // closing the popup STEP #3
delete window.auth_popup;
const code = data?.data; // you will get code here STEP #4
console.log(code);
}
}
function yourfunction { // this probably called when an event occurs
const windowFeatures = "popup";
window.auth_popup = window.open(
"https://www.strava.com/oauth/authorize?client_id=123456&response_type=code&redirect_uri=http://localhost/exchange_token&approval_prompt=force&scope=activity:read_all'",
"Auth",
windowFeatures,
);
}
code
参数并将其
code
发送到 opener 意味着页面打开了弹出窗口。
let params = new URLSearchParams(location.search)
window.opener?.postMessage(// posting a message to the parent window
{
type:"close",
data: params.get('code')
}
);
注意:此脚本必须从重定向网址页面执行