打开并访问chrome扩展程序中的弹出窗口

时间:2013-12-02 05:12:50

标签: javascript google-chrome-extension popupwindow

您好我需要知道如何访问Chrome扩展程序中弹出窗口的内容。目前我已将我的网站设置为chrome扩展名。我需要的是,当我安装扩展程序时,应该打开一个弹出窗口,要求用户名和密码。当用户输入他的用户名和密码时,它应该存储在本地Storage.Currently我能够打开一个弹出窗口。但我不知道如何存储用户输入的名称作为用户名。任何人请帮助我。我无法弄清楚如何做到这一点。 这是manifest.json

{
"name": "Calpine Extension",
"version": "1.0",
"description": "Log on to calpinemate",
"manifest_version": 2,
"browser_action": {
    "default_icon": "icon_128.png"
},
"background": {
    "persistent": false,
    "scripts": ["background.js"]
},

"browser_action": {
    "default_title": "Test Extension",
    "default_icon": "calpine_not_logged_in.png"
},
"permissions": [

   "*://blog.calpinetech.com/test/index.php",
   "alarms",
    "notifications"
     ],
        "web_accessible_resources": [
        "/icon_128.png"]

      }

这是background.js

    var myNotificationID = null;

    var oldChromeVersion = !chrome.runtime;



      function getGmailUrl() {

        return "http://calpinemate.com/";

            }


         function isGmailUrl(url) {

          return url.indexOf(getGmailUrl()) == 0;

         }





       chrome.browserAction.onClicked.addListener(function(tab) {


          chrome.tabs.query({

           url: "http://calpinemate.com/*",

         currentWindow: true
            },
         function(tabs) {

       if (tabs.length > 0) {

       var tab = tabs[0];

       console.log("Found (at least one) Gmail tab: " + tab.url);

       console.log("Focusing and refreshing count...");

       chrome.tabs.update(tab.id, { active: true });

       updateIcon();

        }
      else {

      console.log("Could not find Gmail tab. Creating one...");

       chrome.tabs.create({ url: getGmailUrl() });

       updateIcon();

       }
      });

    });



       function onInit() {

        console.log('onInit');


        updateIcon();

       if (!oldChromeVersion) {

         chrome.alarms.create('watchdog', {periodInMinutes:5});

           }

         }




        function onAlarm(alarm) {

       console.log('Got alarm', alarm);

        if (alarm && alarm.name == 'watchdog') {

        onWatchdog();

          } 
       else {

        updateIcon();

        }

           }


      function onWatchdog() {

      chrome.alarms.get('refresh', function(alarm) {

       if (alarm) {

      console.log('Refresh alarm exists. Yay.');

    } 
     else {
      console.log('Refresh alarm doesn\'t exist!? ' +
              'Refreshing now and rescheduling.');

        updateIcon();

     }
       });

        } 


       if (oldChromeVersion) {

        updateIcon();

         onInit();

        } 

       else {

          chrome.runtime.onInstalled.addListener(onInit);

          chrome.alarms.onAlarm.addListener(onAlarm);

             }




            function updateIcon(){


         var req = new XMLHttpRequest();

         req.addEventListener("readystatechange", function() {

       if (req.readyState == 4) {

       if (req.status == 200) {


       var item=req.responseText;


       if(item==1){

        chrome.browserAction.setIcon({path:"calpine_logged_in.png"});

        chrome.browserAction.setBadgeBackgroundColor({color:[190, 190, 190, 230]});

        chrome.browserAction.setBadgeText({text:""});   

         }

      else{

       chrome.browserAction.setIcon({path:"calpine_not_logged_in.png"});

       chrome.browserAction.setBadgeBackgroundColor({color:[190, 190, 190, 230]});

       chrome.browserAction.setBadgeText({text:""}); 

       chrome.notifications.create(
        'id1',{
       type: 'basic',
       iconUrl: '/icon_128.png',
       title: 'Calpinemate',
        message: 'Hello calpiner',
       buttons: [{ title: 'Mark',
                        iconUrl: '/tick.jpg'
                  },{ title: 'Ignore',
                        iconUrl: '/cross.jpg'}],
       priority: 0},
       function(id) { myNotificationID = id;}
           );


     chrome.notifications.onButtonClicked.addListener(function(notifId, btnIdx) {
    if (notifId === myNotificationID) {
    if (btnIdx === 0) {
        window.open("http://www.calpinemate.com/");
    } else if (btnIdx === 1) {
       notification.close();
    }
    }
     });

     chrome.notifications.onClosed.addListener(function() {
      notification.close();
     });


    }

      } 
   else {

        // Handle the error

        alert("ERROR: status code " + req.status);

       }

    }

         });

            req.open("GET", "http://blog.calpinetech.com/test/index.php", true);

         req.send(null);

   }


  function login() {

/* First retrieve the credentials */
    chrome.storage.local.get(['username', 'password'], function(items) {
    var user = items.username;
    var pass = items.password;

    if (!user || !pass) {

        /* Missing credentials. Prompt the user. */
        chrome.windows.create({ url : "test.html" });
        return;
    }

    /* Log-in */
    // ...code that logs the user in
      });
      }

这是test.html

   <html>
    <head>
    <script type="text/javascript">
        function log(){
            var uname=document.getElementById('name');


             document.getElementById('pp').innerHTML = uname;
        }
      </script>
     </head>
   <body>
    <form name="userinfo" id="userinfo">
    username : 
    <input id="name" type="text" name="username"/><br><br>
    password :
    <input type="password" name="password"/><br><br>
    <input type="button" value="Log In" onclick="log()"/>
    <p id="pp"></p>
    </form>
  </body>
  </html>

test.js

  window.addEventListener('DOMContentLoaded', function() {
   var user  = document.querySelector('input#user');
   var pwd  = document.querySelector('input#pass');
  var form = document.querySelector('form#userinfo');

  form.addEventListener('submit', function(evt) {     
    evt.preventDefault();
    var userStr = user.value; 
    var pwdStr = pwd.value;
   if ((userStr.length === 0) || (passStr.length === 0)) {
        alert('Please, specify both Username and Password !');
        return;
    }
   chrome.runtime.getBackgroundPage(function(bgPage) {
     bgPage.login(userStr,pwdStr); });
    window.close();


   }); 

  });

1 个答案:

答案 0 :(得分:1)

由于 Content Security Policy (CSP) ,内联脚本不会被执行。您应该将代码和事件绑定移动到外部JS文件,并使用 chrome.storage API 来存储用户名和密码。

test.html

<html>
    <head>
        <script type="text/javascript" src="test.js"></script>
    </head>
    <body>
        <form id="userinfo">
            <label for="user">Username:</label>
            <input type="text" id="user" />
            <br />
            <label for="pass">Password:</label>
            <input type="password" id="pass" />
            <br />
            <br />
            <input type="button" id="login" value="Log In" />
        </form>
    </body>
</html>

test.js

window.addEventListener('DOMContentLoaded', function() {
    var user  = document.querySelector('input#user');
    var pass  = document.querySelector('input#pass');
    var login = document.querySelector('input#login');

    login.addEventListener('click', function() {
        var userStr = user.value;
        var passStr = pass.value;

        /* Validate input */
        if ((userStr.length === 0) || (passStr.length === 0)) {
            alert('Please, specify both Username and Password !');
            return;
        }

        /* Store the data */
        chrome.storage.local.set({
            username: userStr,
            password: passStr,
        }, function() {

            if (chrome.runtime.lastError) {

                /* An error occurred. Unable to proceed. */
                // ...handle the error, e.g. inform the user
                return;
            }

            /* Do whatever youneed to, e.g. log-in the user */
            chrome.runtime.getBackgroundPage(function(bgPage) {
                bgPage.login();
            });
        });
    });
});

background.js

...
function login() {

    /* First retrieve the credentials */
    chrome.storage.local.get(['username', 'password'], function(items) {
        var user = items.username;
        var pass = items.password;

        if (!user || !pass) {

            /* Missing credentials. Prompt the user. */
            chrome.windows.create({ url : "test.html" });
            return;
        }

        /* Log-in */
        // ...code that logs the user in
    });
}

(如果他从帐户设置启用该选项,则使用chrome.storage.sync(而不是.local)将在用户的设备上同步数据。)


请注意:

  

不应存储机密用户信息!存储区域未加密。