且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

打开chrome.identity.launchWebAuthFlow作为选项卡(Chrome扩展程序)

更新时间:2023-12-05 19:17:22

您将无法获得OAuth流在弹出窗口中工作,但有一个完整演练,可通过浏览器选项卡自行控制流程。

I am using chrome.identity.launchWebAuthFlow() to direct a user through OAuth2 of a non-Google API when they use my extension.

Even though authentication works and I can effectively get the user's authentication token, I dislike that it opens up entirely in a new window that lacks the browser's UIs and a URL bar.

Ideally, I would be able to conduct this OAuth dance within the extension's popup window. If that doesn't work, being able to at least have this OAuth event take place in a separate tab is another solution.

Right now, the user will click on the extension to open up the popup. On the popup, there is a button that they will click to activate OAuth. From here, a whole other window pops up, but instead I'd like it to stay within the popup (see above).

How can I make this happen? I've seen a lot of talk about it, but no solution for it.

Thanks!

manifest.json

{
    "manifest_version": 2,
    "name": "Extension",
    "version": "0.0.1",
    "permissions": [
        "identity",
        "tabs",
        "http://*/*", 
        "https://*/*"
    ],
    "browser_action":{
        "default_icon": "icon.png",
        "default_popup" : "popup.html"
    },

    "background": {
        "scripts": ["background.js"]
    }
}

background.js

chrome.runtime.onMessage.addListener(
    function(request, sender, sendResponse){
        if( request.message==="start_oauth"){
            chrome.identity.launchWebAuthFlow(
                {
                    "url" : "https://example.com/manage/oauth2/authorize?callback_uri="
                    +encodeURIComponent(<callback_uri>)
                    +"&client_id=" + <client_id>
                    +"&response_type=code",
                "interactive" : true
                },
                function(redirect_url){
                    var auth_token = redirect_url.substr(<callback_uri>.length+6);
                }
            );
        }
    }
);

popup.js

function startOAuth(){
    chrome.runtime.sendMessage({"message": "start_oauth"});
}
document.getElementById("login").addEventListener("click", startOAuth);

popup.html

<html>
    <body>
        <button id="login"> Click here to log in</button>
    </body>
    <script src="popup.js"></script>
</html>

You won't be able to get the OAuth flow working in a popup but there is a full walkthrough of controlling the flow yourself with browser tabs.