popup 可以通过 chrome.tabs.sendMessage 函数向 content 发送消息,示例如下 :
popup.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
*{padding:0; margin:0; font-size:14px;}
.menu{width:300px; padding:15px;}
.menu-item{line-height:36px; cursor:pointer; opacity:0.92;}
.menu-item:hover{opacity:1;}
.h3{font-size:15px; line-height:50px;}
</style>
</head>
<body>
<div class="menu">
<h3 class="h3">菜单页面</h3>
<div class="menu-item" id="menu-1">菜单1</div>
<div class="menu-item" id="menu-2">菜单2</div>
</div>
<script src="js/jquery.js"></script>
<script src="js/popup.js"></script>
</body>
</html>
popup.js
// popup.js
$('#menu-2').click(function(){
// popup 向 content 发送消息示例
chrome.tabs.query(
{'active': true, 'lastFocusedWindow': true},
function(tabs) {
chrome.tabs.sendMessage(
tabs[0].id,
{cmd:'test', value:'你好,我是popup!'},
function(response){
alert(response);
})
;
}
);
});
content.js
/* content-script */
console.log('content-script 运行了 ...');
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse)
{
console.log(request);
console.log(sender);
if(request.cmd == 'test'){
$('input').val('hi..');
sendResponse('我收到了你的消息!');
}
});