Firefox附加组件:(原生应用程序+内容脚本+后台脚本)消息 [英] Firefox add-on: (Native app + Content Script + Background script) messaging

查看:563
本文介绍了Firefox附加组件:(原生应用程序+内容脚本+后台脚本)消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究一个简单的插件,可以解析页面的文本,例如twitter.com,然后发送一个外部脚本并接收响应。
我拥有的当前工作流程如下所示:


  1. 从内容脚本连接到后台脚本。


  2. 然后从后台脚本连接到本地应用程序,并接收响应


  3. 格式并传递响应到最后可以更改DOM的内容脚本。

我在连接到后台时收到以下错误脚本。
错误:
$ b

错误:尝试在断开的端口上发送postMessage

当错误出现在 content.js:10:17 这是:
$ b

  myPort.postMessage({idx:i,str:他们点击了页面!}); 

我无法解决这个错误。

content.js
$ b

  console.log(LOADED !); 
var currentTweetIndex = 0;
var tweets = null;
var myPort = browser.runtime.connect({name:port-from-cs}); //连接到后台脚本
//myPort.postMessage({str:hello from content script});

函数AnalyzeTweets(){
tweets = document.getElementsByClassName('tweet-text');
for(var i = 0; i< tweets.length; i ++){
myPort.postMessage({idx:i,str:they clicked the page!


函数ColorTweet(index,tweet_class){
var A = tweets [index];
if(tweet_class ==neutral){
color =green;
} else if(tweet_class ==toxic){
color =yellow;
} else if(tweet_class ==hateful){
color =red;
} else {
console.log(UNKNOWN CLASS RECEIVED);
}
A.parentElement.style.backgroundColor = color;


myPort.onMessage.addListener(function(m){
console.log(In content script,received message from background script:);
console.log(m.idx +:+ m.tweet_class);
ColorTweet(m.idx,m.tweet_class);
});
document.body.addEventListener(click,function(){
AnalyzeTweets();
// myPort.postMessage({str:they clicked the page!});
});

background.js

/ *启动时,连接到ping_pong应用程序。 * /
var port = browser.runtime.connectNative(ping_pong);
var portFromCS; //从内容脚本连接

/ *从本地应用程序收听消息。 * /
port.onMessage.addListener((response)=> {
console.log(Received:+ response);
portFromCS.postMessage({tweet_class:toxic, idx:1});
//发送对内容脚本的响应
});

/ *点击浏览器动作,发送应用消息。 * /
browser.browserAction.onClicked.addListener(()=> {
console.log(Sending:pinggasdfasdfas);
port.postMessage(tested!);
});

////////////////////////////////////////// //////////////////////////
///监听来自content-script的连接
函数connected(p){
portFromCS = p;
portFromCS.onMessage.addListener(function(m){
console.log(>在后台脚本中,收到来自内容脚本的消息)
console.log(m);
port.postMessage(m);
});
}
browser.runtime.onConnect.addListener(connected);
//browser.browserAction.onClicked.addListener(function(){
// portFromCS.postMessage({tweet_class:toxic,idx:1});
//});

manifest.json


$ b $ {
description:本地消息示例附加组件,
manifest_version:2,
name:原生消息示例,
version:1.0,
图标:{
48:icons / message.svg






$ id $ b $ strict_min_version $: 50.0
}
},

background:{
scripts:[background.js]
},
$ bcontent_scripts:[
{
matches:[*://*.twitter.com/*],
js:[ content.js]
}
],

browser_action:{
default_icon:icons / message.svg
},

permissions:[nativeMessaging]
}

解决方案

显然,上述逻辑起作用。问题是,在任何更改后加载插件后,我们需要重新加载选项卡以设置native-app + background-script + content-script之间的连接,否则会引发上述错误。

b $ b

I am working on a simple add-on that can parse the text of a page, example twitter.com, and then send it an external script and receive the response. The current workflow that I have is like this:

  1. Connect to background script from content script.

  2. Then Connect to native App from background script and receive the response

  3. Format and pass the response to the content script which can finally make changes to the DOM.

I am receiving the following error when connecting to background script. Error:

Error: Attempt to postMessage on disconnected port

while the error is on line content.js:10:17 which is:

myPort.postMessage({idx: i, str: "they clicked the page!"});

I am not able to resolve this error.

content.js

console.log("LOADED!");
var currentTweetIndex = 0;
var tweets = null;
var myPort = browser.runtime.connect({name:"port-from-cs"}); //Connect to background script
//myPort.postMessage({str: "hello from content script"});

function AnalyzeTweets(){
        tweets = document.getElementsByClassName('tweet-text');
        for(var i = 0; i < tweets.length; i++) {
                myPort.postMessage({idx: i, str: "they clicked the page!"});
        }
}
function ColorTweet(index, tweet_class) {
        var A = tweets[index];
        if(tweet_class == "neutral"){
                color = "green";
        } else if (tweet_class == "toxic"){
                color = "yellow";
        } else if (tweet_class == "hateful") {
                color = "red";
        } else {
                console.log("UNKNOWN CLASS RECEIVED");
        }
        A.parentElement.style.backgroundColor = color;
}

myPort.onMessage.addListener(function(m) {
        console.log("In content script, received message from background script: ");
        console.log(m.idx + ": " + m.tweet_class);
        ColorTweet(m.idx, m.tweet_class);
});
document.body.addEventListener("click", function() {
        AnalyzeTweets();
        //       myPort.postMessage({str: "they clicked the page!"});
});

background.js

/* On startup, connect to the "ping_pong" app. */
var port = browser.runtime.connectNative("ping_pong");
var portFromCS; // connection from content script

/* Listen for messages from the native app. */
port.onMessage.addListener((response) => {
        console.log("Received: " + response);
        portFromCS.postMessage({tweet_class: "toxic", idx: 1});
        // Send response to content script
});

/* On a click on the browser action, send the app a message. */
browser.browserAction.onClicked.addListener(() => {
        console.log("Sending:  pinggasdfasdfas");
        port.postMessage("tested!");
});

////////////////////////////////////////////////////////////////////
/// Listen for connection from content-script
function connected(p) {
        portFromCS = p;
        portFromCS.onMessage.addListener(function(m) {
                console.log("> In background script, received message from content script")
                console.log(m);
                port.postMessage(m);
        });
}
browser.runtime.onConnect.addListener(connected);
//browser.browserAction.onClicked.addListener(function() {
//       portFromCS.postMessage({tweet_class: "toxic", idx: 1});
//});

manifest.json

{
        "description": "Native messaging example add-on",
        "manifest_version": 2,
        "name": "Native messaging example",
        "version": "1.0",
        "icons": {
                "48": "icons/message.svg"
        },

        "applications": {
                "gecko": {
                        "id": "ping_pong@example.org",
                        "strict_min_version": "50.0"
                }
        },

        "background": {
                "scripts": ["background.js"]
        },

        "content_scripts": [
                {
                        "matches": ["*://*.twitter.com/*"],
                        "js": ["content.js"]
                }
        ],

        "browser_action": {
                "default_icon": "icons/message.svg"
        },

        "permissions": ["nativeMessaging"]
}

解决方案

Apparently, the above logic works. The issue was that after loading the addon after any changes, we need to reload the tab to setup a connection between the native-app + background-script + content-script, otherwise it throws the above-mentioned error.

这篇关于Firefox附加组件:(原生应用程序+内容脚本+后台脚本)消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆