从网页按钮单击调用chrome扩展中的javascript方法

时间:2015-01-31 10:32:59

标签: html5 javascript-events google-chrome-extension

我在chrome中添加了this chrome扩展程序。我从here获取了扩展程序代码。现在我想从我的网页“tack shot”按钮点击类似下面的内容

触发此扩展
<html>
<head>
<script>
function takeShot(){
    //code to trigger chrome extension script.
}
</script>
</head>
<body>
<button onClcik='takeShot()'>take shot</button>
</body>
</html>

任何人都可以帮我解决这个问题。提前谢谢。

1 个答案:

答案 0 :(得分:0)

https://developer.chrome.com/extensions/messaging#external-webpage

的manifest.json

{
    "name": "My Extension",
    "version": "1.0",
    "manifest_version": 2,
    "background": {
       "scripts": ["background.js"]
    },
    "externally_connectable": {
        "matches": ["http://www.example.com/*"]
    }
}

background.js

chrome.runtime.onMessageExternal.addListener(
  function(request, sender, sendResponse) {
    // your code in exstension
  });

http://www.example.com/

    <html>
    <head>
    <script>
   var extensionId = "your exstension id here";
    function takeShot(){
        chrome.runtime.sendMessage(extensionId, yourMessage,
            function(response) {
                if (!response.success)
                    console.log('error');
            });
    }
    </script>
    </head>
    <body>
    <button onClick='takeShot()'>take shot</button>
    </body>
    </html>