Alert is not working in pop up window in chrome ex

2019-02-28 11:20发布

问题:

Could any one help me,to find out my problem.I have set my website as chrome extension.When I install the extension,it navigates to a popup window asking user name and password along with a login button. But when I tried to alert the username entered by the user in javascript,it is not working.Anyone please help me.What would be the reason? Here is my 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"]

 }

Here is my code that creates a pop up window on installation

      chrome.windows.create({url : "test.html"}); 

here is my test.html

<html>
<head>
    <script type="text/javascript">
        function log(){
            var uname=document.getElementById('name');
           alert(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>

回答1:

The reason it is not working is that test.html is opened as a "view" of your extension and the Content Security Policy (CSP) prevents inline scripts and inline event-binding from being executed.

You should move the code and the event-bindings to an external JS file.

In test.html:

<html>
    <head>
        <script type="text/javascript" src="test.js"></script>
    </head>
    <body>
        ...
        <input type="button" id="login" value="Log In" />
        ...
    </body>
</html>

In test.js:

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

    login.addEventListener('click', function() {
        // ...do stuff...
    });
});


回答2:

You have to pick up value of the input field:

var uname = document.getElementById('name').value;