如何在chrome浏览器扩展中执行javascript

时间:2014-04-19 06:44:55

标签: javascript html google-chrome google-chrome-extension

我正在尝试为Google Chrome进行扩展,我需要在Chrome扩展程序中执行一个简单的javascript来打开网址我知道锚标记可以做到这一点,但我想在js中添加一些其他功能。

将执行javascript的简单pop.html文件是:

<html>
<body>
<form>
<div id="search_panel">

<input type="text" id="box" name="txt" required placeholder="Search anything"/> <input type="submit" id="stu_submit" onclick="hey();" name="stu_post" value="Search"/>
<div> <a href="http//s.com" target="_blank" id="stu_links" >s.com</a> <a href="#" id="stu_links">news</a> <a href="#" id="stu_links">hey</a> <a href="#" id="stu_links">Sign In</a> </div>
</div>
<script>
    function hey()
    {
    window.open('http://www.google.com');
    }
  </script>
</form>
</body>
</html>

并且清单文件是:

{
  "name": "Chrome Extension for s.com",
  "version": "1.0",
  "manifest_version": 2,
  "description": "Google Chrome Extension for s.com.",
  "browser_action": 
  {
    "default_icon": "img/icon.png",
    "default_menu": "FirstMenu",
    "default_popup": "popup.html"
  },

   "chrome_url_overrides" : {
    "newtab": "s.html"
  },

  "permissions": [
    "http://api.flickr.com/"
  ]
}

请帮助并告诉如何在popup.html中执行js

1 个答案:

答案 0 :(得分:0)

这可能会对您有所帮助:Run Javascript in Chrome Extension -> Basic?

复制到此处以供快速参考:

根据chrome扩展文档,

不会执行内联JavaScript。此限制禁止内联<script>块和内联事件处理程序(例如<button onclick="...">)。

阅读:http://developer.chrome.com/extensions/contentSecurityPolicy.html#JSExecution

在popup.js中用作

document.addEventListener('DOMContentLoaded', function () {
      document.querySelector('button').addEventListener('click', main);      
});
function main() {
    var source = document.getElementById('source').value;
    document.getElementById("result").innerHTML = source;
}