在chrome扩展的弹出窗口中,警报不起作用

Alert is not working in pop up window in chrome extension

本文关键字:不起作用 窗口 chrome 扩展      更新时间:2024-02-07

有人能帮我找出我的问题吗。我已将我的网站设置为chrome扩展。当我安装扩展时,它会导航到一个弹出窗口,询问用户名和密码以及登录按钮。但当我试图提醒用户在javascript中输入的用户名时,它不起作用。有人请帮帮我。原因是什么?这是我的宣言.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"]
 }

这是我在安装时创建弹出窗口的代码

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

这是我的测试.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>

它不起作用的原因是test.html是作为扩展的"视图"打开的,并且内容安全策略(CSP)阻止执行内联脚本和内联事件绑定。

您应该将代码和事件绑定移动到外部JS文件中。

test.html中

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

测试.js中

window.addEventListener('DOMContentLoaded', function() {
    var login = document.querySelector('input#login');
    login.addEventListener('click', function() {
        // ...do stuff...
    });
});

您必须获取输入字段的值:

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