edge扩展开发-页面间的通信

1. popup.html

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="content-type" content="text/html;charset=utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <script src="js/jquery.min.js"></script>
        <script src="js/popup.js"></script>
    </head>
    <body>
        <input id="test_button" type="button" value="测试">
    </body>
</html>

2. popup.js

$(document).ready(function(){
    $("input[id='test_button']").click(function(){
        chrome.tabs.getSelected(null, function(tab) {
            chrome.tabs.sendMessage(tab.id, {greeting: "test_button"}, function(response) {
                console.log(response);
            })
        });
    });
});

3. content.js

$(document).ready(function(){
    chrome.extension.onMessage.addListener(function(request, sender, sendMessage) {
        if (request.greeting == "test_button") {
            alert('hello world');
            sendMessage('hello world');
        }
    });
});
posted @ 2023-03-10 23:04  wstong  阅读(72)  评论(0编辑  收藏  举报