2013-02-10 52 views
8

所以我测试了创建铬扩展。我明白,在Manifest v2中,您无法在popup.html中使用JavaScript。所以,我已将javascript移至单独的文件popup.js。超简单的Chrome扩展不会添加EventListener到按钮onclick事件

我想要一个简单的按钮在弹出窗口中调用hello world警报,但它根本不起作用。

此外,Chrome的Inspect Element调试器不显示任何错误。

popup.html

<html> 
    <head> 
     <title>Test</title> 
     <script language='javascript' src='popup.js'></script> 
    </head> 
    <body> 
     <form name='testForm'> 
      <input type='button' id='alertButton' value='click me'> 
     </form> 
    </body> 
</html> 

popup.js

function myAlert(){ 
    alert('hello world') 
} 

window.onload = function(){ 
    document.addEventListener('DOMContentLoaded', function() { 
     document.getElementById('alertButton').addEventListener('onclick', myAlert); 
    }); 
} 

manifest.json的

{ 
    "manifest_version": 2, 
    "name": "Test", 
    "description": "Test Extension", 
    "version": "1.0", 

    "icons": { 
    "48": "icon.png" 
    }, 

    "permissions": [ 
    "http://*/*", 
    "https://*/*" 
    ], 

    "browser_action": { 
    "default_title": "This is a test", 
    "default_icon": "icon.png", 
    "default_popup": "popup.html" 
    } 
} 

任何想法?

回答

12

只是删除window.onload

function myAlert(){ 
    alert('hello world'); 
} 

document.addEventListener('DOMContentLoaded', function() { 
    document.getElementById('alertButton').addEventListener('click', myAlert); 
}); 
+1

谢谢!我还注意到,我在事件监听器中使用“onclick”而不是“click”作为事件。唷! – LittleBobbyTables 2013-02-10 19:10:02

+0

Thnx .....我也在这里挣扎了2个小时。没想到会删除window.onload ... thnx再次:) – 2013-08-20 07:37:49

+0

不适用于'options.js' – user924 2017-09-02 11:47:05

相关问题