繁体   English   中英

从 web 页面按钮点击调用 Chrome 扩展中的 JavaScript 方法

[英]Call JavaScript method in Chrome extension from web page button click

我已 将此chrome 扩展程序添加到 Chrome。 我从这里拿了扩展代码。 现在我想从我的 web 页面“tack shot”按钮触发这个扩展,点击如下内容:

<html>
<head>
<script>
function takeShot(){
    //code to trigger chrome extension script.
}
</script>
</head>
<body>
<button onClick='takeShot()'>take shot</button>
</body>
</html>

谁能帮我解决这个问题?

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

清单.json

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

背景.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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM