如何在弹出窗口中添加操作按钮并导航到chrome扩展中的网站?

时间:2013-12-13 10:13:05

标签: google-chrome-extension popupwindow

我需要在2种不同的情况下显示2个弹出窗口。目前我正在检查服务器文件并将其凭据存储在localStorage中。每当用户点击扩展时,它应该检查localStorage是否是如果它是空的,那么应该看到一个弹出窗口并询问他的用户名。这个存储在localstorage中。当用户点击图标时,localstorage不是空的,所以它应该显示另一个pop showind一个用户名的字段,有2个按钮,即“更改设置”和“转到网站”。当用户点击更改设置时,弹出shuuld再次出现询问用户名。如果他点击进入网站,它应该导航到如何做到这一点?请帮帮我。我试过按钮按钮不起作用。第二次弹出窗口只在重新加载扩展时显示。请帮帮我。 这是我的background.js

这是我更新的popup.js

  window.addEventListener('DOMContentLoaded', function() {   
  var divLoading  = document.querySelector('div#loadingContainer');
  var divSettings = document.querySelector('div#settingsContainer');
  var divLoggedIn = document.querySelector('div#loggedInContainer');
  var divChange = document.querySelector('div#settingsChange');


 var user1 = divSettings.querySelector('input#user1');
 var form  = divSettings.querySelector('form#userinfo');


 var user2   = divLoggedIn.querySelector('span#user2');   
 var change  = divLoggedIn.querySelector('input#change');
 var calpine = divLoggedIn.querySelector('input#calpine');

 var user3 = divChange.querySelector('input#user3');
 var form3  = divChange.querySelector('input#changeset');
 var cancel = divChange.querySelector('input#emailcancel');


 var user = localStorage.username;
  if (user) {

   // user1.value = user2.value = user;
   user1.value = user2.textContent = user;
    user3.value = user;        
    divLoggedIn.style.display = 'block';
    divSettings.style.display = 'none';
    divChange.style.display = 'none';      
    } else {

    divSettings.style.display = 'block';
    divChange.style.display = 'none';
    divLoggedIn.style.display = 'none';      
    user1.focus();
    user1.select();
    }
   divLoading.style.display = 'none';


    form.addEventListener('submit', function(evt) {
    evt.preventDefault();
    var userStr = user1.value;
    chrome.runtime.getBackgroundPage(function(bgPage) {
        bgPage.login(userStr);
    });
    window.close();
     });

   form3.addEventListener('click', function() {

    var userStr = user3.value;

    chrome.runtime.getBackgroundPage(function(bgPage) {
        bgPage.login(userStr);
    });
    window.close();
    });

   change.addEventListener('click', function(evt) {
    divLoggedIn.style.display = 'none';
    divSettings.style.display = 'none';
    divChange.style.display = 'block';

    user3.focus();
    user3.select();
   });

   cancel.addEventListener('click', function() {
    divLoggedIn.style.display = 'block';
    divSettings.style.display = 'none';
    divChange.style.display = 'none';

    user3.focus();
    user3.select();
    });


    calpine.addEventListener('click', function() {
    chrome.tabs.create({ url: 'http://www.calpinemate.com/' });
    });
    });

我已经做了一些更改,因为我被要求这样做。我添加了一个名为divchange的新div。 这是我更新的userinfo.html

  <!DOCTYPE html>
   <html>
   <head>

    <script type="text/javascript" src="popbak.js"></script>       
  </head>
     <body>

    <div id="loadingContainer"></div>
    <div id="settingsContainer">
        <b>Please Enter your Email ID/Employee Code</b>
        <br />
        <br />
        <form id="userinfo">
            <table>
                <tr><td> <label for="user">Email/Employee Code:</label></td>
                    <td>    <input type="text" id="user1" required /></td></tr>
                <tr><td> <input type="submit" id="login" value="Log In" /></td></tr>
            </table>
        </form>
       </div>
       <div id="settingsChange">
        <b>Please Enter your Email ID/Employee Code</b>
        <br />
        <br />

            <table>
                <tr><td><label for="user">Email/Employee Code:</label></td>
                    <td><input type="text" id="user3" required /></td></tr>
                <tr><td><input type="button" id="emailchange" value="Change" /></td>
                    <td><input type="button" id="emailcancel" value="Cancel" /></td>                         </tr>
               </table>

        </div> 

      <div id="loggedInContainer">
        <table>
            <tr><td>   <label for="user">Email/Employee Code:</label></td>

      <!--   <input type="text" id="user2" readonly /> -->
         <td><span id="user2"></span></td> </tr>   
        <br />
        <tr><td><input type="button" id="calpine" value="Go to Calpinemate"/></td>
            <td><input type="button" id="change" value="Change Settings"/></td></tr>
        </table>
         </div>
         </body>
      </html>

这是我的bgpage.login()

   function login(useremail){
     if(!useremail)
    {
  alert('Please enter your Email/Employee code');  //this is not working
 return;
   } 
  var urlPrefix = 'http://www.calpinemate.com/employees/attendanceStatus/';
   var urlSuffix = '/3';
   var req1 = new XMLHttpRequest();
   req1.addEventListener("readystatechange", function() {   
    if (req1.readyState == 4) {
    if (req1.status == 200) {          
    var item=req1.responseText;           
    if(item==1){
     localStorage.username=useremail;  
                 updateIcon();             
     }
      else
       {
           alert('Please enter a valid Email/employee code');
               updateIcon();

       }
     }
    else {
      alert("ERROR: status code " + req1.status);
     }
      }
       });

   var url = urlPrefix + encodeURIComponent(useremail) + urlSuffix;
   req1.open("GET", url);    
    req1.send(null);       
    }

这是我的background.js

var myNotificationID = null;
 var oldChromeVersion = !chrome.runtime;


  setInterval(function() {
      updateIcon();
      }, 1000); 

     function getGmailUrl() {
        return "http://calpinemate.com/";

      }


      function isGmailUrl(url) {
      return url.indexOf(getGmailUrl()) == 0;

          }




    function onInit() {

   updateIcon();

       if (!oldChromeVersion) { 

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

          }



        function onAlarm(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 {
   updateIcon();

      }
    });

     }



     if (oldChromeVersion) {
       updateIcon(); 
        onInit();

          } 

       else {

    chrome.runtime.onInstalled.addListener(onInit);

        chrome.alarms.onAlarm.addListener(onAlarm);

     }




    function updateIcon(){
      if(localStorage.username){

    var urlPrefix = 'http://www.calpinemate.com/employees/attendanceStatus/';
     var urlSuffix = '/2';

        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:""});  

        chrome.notifications.clear('id1', function(){});

         }

      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: '/calpine_not_logged_in.png',
       title: 'Warning : Attendance',
        message: 'Please mark your Attendance !',
       buttons: [{ title: 'Mark',
                        iconUrl: '/tick.jpg'
                  },{ title: 'Ignore',
                        iconUrl: '/cross.jpg'}],
       priority: 0},
       function(id) { myNotificationID = id;}
     );    

        }

      } 
   else {

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

       }

    }

          });
   var url = urlPrefix + encodeURIComponent(localStorage.username) + urlSuffix;
    req.open("GET", url);


   req.send(null);
     }
    }



     onInit();

1 个答案:

答案 0 :(得分:1)

首先,背景页面的localStorage和弹出窗口的localStorage是而不是相同的对象。 此外,每次弹出窗口时,都会重新加载,因此localStorage为空。
更新:Thx到rsanchez的评论,我更正了我的错误:弹出窗口共享扩展的localStorage对象(与背景页面的对象相同)。
您应该使用background-page的localStorage。 (请记住,这只有 ,因为你有一个持久的背景页面!)

最简单(也是最可靠)的方法是使用一个带有两个不同div的弹出窗口(一个用于输入凭据,一个用于登录)并且一次只显示一个。

E.g:

1)从后台页面中删除任何chrome.browserAction.onClicked...侦听器(不会因为它永远不会被触发而将其留在那里,但是将来会让你感到困惑)。

2)在你的清单中声明一个弹出窗口(如果你还没有做过):

<pre>
...
"browser_action": {
    ...
    "default_popup": "popup.html"
},
...
</pre>

3)。使用以下代码创建名为popup.html的文件:

<!DOCTYPE html>
<html>
    <head>
        <script type="text/javascript" src="popup.js"></script>       
    </head>
    <body>
        <div id="loadingContainer"><h3>Loading...</h3></div>
        <div id="settingsContainer" style="display:none;">
            <b>Enter your Email ID/Employee Code</b>
            <br />
            <br />
            <form id="userinfo">
                <label for="user">Email/Employee Code:</label>
                <input type="text" id="user1" required />
                <input type="submit" id="login" value="Log In" />
            </form>
        </div>
        <div id="loggedInContainer" style="display:none;">
            <label for="user">Email/Employee Code:</label>
            <!--<input type="text" id="user2" readonly />-->
            <span id="user2"></span>
            <br />
            <input type="button" id="calpine" value="Go to Calpinemate"/>
            <input type="button" id="change" value="Change Settings"/>
        </div>
    </body>
</html>
</pre>

4)使用以下代码创建名为popup.js的文件:

window.addEventListener('DOMContentLoaded', function() {

    /* Container divs */
    var divLoading  = document.querySelector('div#loadingContainer');
    var divSettings = document.querySelector('div#settingsContainer');
    var divLoggedIn = document.querySelector('div#loggedInContainer');

    /* Settings-container fields */
    var user1 = divSettings.querySelector('input#user1');
    var form  = divSettings.querySelector('form#userinfo');

    /* LoggedIn-container fields */
    //var user2   = divLoggedIn.querySelector('input#user2');
    var user2   = divLoggedIn.querySelector('span#user2');
    var change  = divLoggedIn.querySelector('input#change');
    var calpine = divLoggedIn.querySelector('input#calpine');

    /* Query the extension's localStorage
     * in order to decide which DIV to show */
    var user = localStorage.username;
    if (user) {
        /* 'Username' is set: Show the LoggedIn-container
         * (after updating the value of the (readonly) '#user' field) */
        //user1.value = user2.value = user;
        user1.value = user2.textContent = user;
        divLoggedIn.style.display = 'block';
    } else {
        /* 'Username' is not set: Show the Settings-container */
        divSettings.style.display = 'block';
        user1.focus();
        user1.select();
    }
    divLoading.style.display = 'none';

    /* Listener for '#userinfo' form */
    form.addEventListener('submit', function(evt) {
        evt.preventDefault();
        var userStr = user1.value;
        chrome.runtime.getBackgroundPage(function(bgPage) {
            bgPage.login(userStr);
        });
        window.close();
    });

    /* Listener for '#change' button */
    change.addEventListener('click', function(evt) {
        divLoggedIn.style.display = 'none';
        divSettings.style.display = 'block';
        user1.focus();
        user1.select();
    });

    /* Listener for '#calpine' button */
    calpine.addEventListener('click', function() {
        chrome.tabs.create({ url: 'https://your.domain.goes/here' });
    });
});