Rya*_*ush 10 sendmessage google-chrome-extension
我正在尝试使用简单的Google Chrome扩展程序来处理消息/变量流经以下每个步骤...
我已经想出了如何将消息/变量发送到 Background.js并从一个方向(Background.js -> Popup.js或Background.js -> Contentscript.js)发送,但无法通过所有三个成功(Contentscript.js -> Background.js -> Popup.js).以下是我演示中的文件.
大教堂
<h1 class="name">Joe Blow</h1>
Content.js
fromDOM = $('h1.name').text();
chrome.runtime.sendMessage({contentscript: "from: contentscript.js", title: fromDOM}, function(b) {
console.log('on: contentscript.js === ' + b.background);
});
Run Code Online (Sandbox Code Playgroud)
Background.js
chrome.tabs.getSelected(null, function(tab) {
chrome.extension.onMessage.addListener(function(msg, sender, sendResponse) {
sendResponse({background: "from: background.js"});
console.log('on: background.js === ' + msg.title);
});
});
Run Code Online (Sandbox Code Playgroud)
Popup.js
chrome.extension.sendMessage({pop: "from: popup.js"}, function(b){
console.log('on: popup.js === ' + b.background);
$('.output').text(b.background);
});
Run Code Online (Sandbox Code Playgroud)
Popup.html
<html>
<head>
<script src="jquery.js"></script>
<script src="popup.js"></script>
</head>
<body>
<p class="output"></p>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
的manifest.json
{
"name": "Hello World",
"version": "1.0",
"manifest_version": 2,
"description": "My first Chrome extension.",
"background" : {
"scripts": ["background.js"]
},
"permissions": [
"tabs"
],
"browser_action": {
"default_icon": "icon.png",
"default_popup": "popup.html"
},
"content_scripts": [
{
"matches": ["http://*/*"],
"js": ["jquery.js","contentscript.js"],
"run_at": "document_end"
}
]
}
Run Code Online (Sandbox Code Playgroud)
我有一种感觉,我知道这次旅行是什么,但文件严重缺乏,manifest_version: 2因为它难以破译.一个简单,可重用的例子对学习过程非常有帮助,因为我确信这是一个常见的问题.
Bea*_*ist 20
好吧,改变代码中的一些东西应该让它像你想要的那样工作.并非所有我要做的改变都是必要的,但这就是我可以做到的.
内容脚本
var fromDOM = $('h1.name').text();
chrome.runtime.sendMessage({method:'setTitle',title:fromDOM});
Run Code Online (Sandbox Code Playgroud)
背景
var title;
chrome.runtime.onMessage.addListener(function(message,sender,sendResponse){
if(message.method == 'setTitle')
title = message.title;
else if(message.method == 'getTitle')
sendResponse(title);
});
Run Code Online (Sandbox Code Playgroud)
Popup.js
chrome.runtime.sendMessage({method:'getTitle'}, function(response){
$('.output').text(response);
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6575 次 |
| 最近记录: |