[英]Using Facebook javascript SDK from extension script
這是我來自 chrome 擴展的background.js
:
window.addEventListener("load", function() {
const fbConnect = new Promise(function(resolve, reject) {
const script = document.createElement("script");
script.onload = resolve;
script.onerror = reject;
script.async = true;
script.src = "https://connect.facebook.net/en_US/sdk.js";
document.body.appendChild(script);
});
});
window.fbAsyncInit = function() {
FB.init({
appId: null,
version: 'v4.0'
});
FB.api("/me", {fields: "last_name"}, function(response) {
console.log(response);
});
};
它給了我以下錯誤:
無法再從 http 頁面調用方法 FB.api。 https://developers.facebook.com/blog/post/2018/06/08/enforce-https-facebook-login/
現在做什么? 是否可以從擴展中使用這個東西? 如果是這樣,我如何告訴 Facebook 服務器這是一個 https 請求?
感謝@misorude和他鏈接的問題,我設法解決了這個問題,使用手動身份驗證而不是 JS SDK。
把它們放在一起是一件很痛苦的事情,因為文檔提供的例子很糟糕,所以我希望它對其他人有用。
這是后台腳本中的一段代碼:
const options = {
url: "https://www.facebook.com/dialog/oauth?client_id=<app-id>&response_type=token&redirect_uri=" + browser.identity.getRedirectURL(),
interactive: true
};
// <app-id> can be found on https://developers.facebook.com/apps/ once you create a new app.
// You must add the URL returned by getRedirectURL() to the app's domain on the page above, otherwise Facebook will return an error.
// getRedirectURL() creates a https:// alias from the extension's browser-extension:// URL.
// The "interactive" key has to be true, otherwise Facebook will return an error.
window.addEventListener("load", function(){
// Launch the authentication process
browser.identity.launchWebAuthFlow(options).then(function(url){
// Mine the access token out of the URL returned by Facebook
let token = new URL(url).hash.match(/(access\_token=)(.*)(&)/)[2];
// I don't know why, but the whole query part is served as a hash, so URLSearchParams() won't work.
// Anyway, the 2nd capture group gives back only the access token string, so we are good.
// Now we are connected, time to ask some information from Facebook (for example id and name)
window.fetch("https://graph.facebook.com/me?fields=id,name&access_token=" + token).then(function(response){
// Parse the response body of the promise
response.json().then(function(data){
console.log(data);
// -> {id: "<your-user-id>", name: "<your-name>"}
});
});
}).catch(function(error){
console.error(error);
});
});
我已經使用了 webExtension 平台的browser
命名空間,但是chrome
命名空間應該也能工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.