如果从后台发送响应,则在内容脚本中执行一个函数 [英] execute a function in content script if response is sent from Background

查看:113
本文介绍了如果从后台发送响应,则在内容脚本中执行一个函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于我的Chrome扩展程序,我试图将选定的文本发布到PHP网页。在本网站上解决了一个问题( Chrome扩展程序:如何捕获选定的文本并发送到Web服务)已经帮助我实现了这一点,但我想用不同的方式发布文本。

而不是XMLHttpRequest如上所述,我想从内容脚本发送一个隐藏的JS表单。此方法允许我在将文本导入到数据库之前查看或更改文本。



问题是从后台获取触发器到内容脚本。我已经有了一条消息,所以需要使用函数(响应)。但是,在sendMessage之外,我无法听到response.cmd。而在sendMessage里面,我无法获得response.cmd来触发一个函数。有没有解决方案,除了从后台脚本发送全新的消息?
我引用的代码:

Background.js

  chrome.extension.onMessage.addListener(function(request,sender,sendResponse){
if(request.cmd ==createSelectionMenu){
sendResponse({cmd:saveText}) ; //做事
}
});

Content_script.js

  chrome.extension.sendMessage({cmd:createSelectionMenu,data:selectedText},
function(response){
if(response.cmd ==saveText){
createForm();
}
}
});


解决方案

我所做的是:



我跟踪自己打开的标签



内容脚本

  //连接到后台脚本
var port = chrome.extension.connect();

后台脚本

  //一个tab请求连接到后台脚本
chrome.extension.onConnect.addListener(function(port){
var tabId = port.sender。 (tabId);
console.log = -1){
channelTabs.push(tabId);
}

//关闭/移动到另一个网址时移除
port.onDisconnect.addListener(function (){
channelTabs.splice(channelTabs.indexOf(tabId),1);
});
});

现在,我可以通过我的后台脚本通知所有已注册的选项卡(即内容脚本)发生:

  var notification = {foo:'bar'}; 
for(var i = 0,len = channelTabs.length; i< len; i ++){
chrome.tabs.sendMessage(channelTabs [i],notification,function(responseMessage){
//从内容脚本返回的消息
console.log(responseMessage);
});
}

再次,在内容脚本的另一面,您可以添加一个监听这些消息:
$ b $ pre $ chrome.extension.onMessage.addListener(function(request,sender,sendResponse){
if(request.foo =='bar'){
executeStuff();
//如果给出回调:
sendResponse&& sendResponse('success');
}
});

这是一种脑力劳动,因为它在某些地方是多余的。但我最喜欢这种方式,因为你可以把它包起来,让它更容易一些。



如果你想看看我是如何使用它的,请参阅我的存储库GitHub: chrome-extension-communicator


For my Chrome extension, I am attempting to post selected text to a PHP webpage. A solved question on this website (Chrome Extension: how to capture selected text and send to a web service) has helped me a lot in achieving this, but I want a different way of posting the text.
Instead of XMLHttpRequest as mentioned there, I want to send a hidden JS form from the content script. This method allows me to view or change the text before importing it to the database.

The problem is to get the trigger from the background to the content script. I already have a message the other way, so using the function(response) is desired. However, outside the "sendMessage", I can’t listen for the response.cmd. And inside the "sendMessage", I can’t get the response.cmd to trigger a function. Is there a solution for this, other than sending an all new message from the background script? The code I am referring to:

Background.js

chrome.extension.onMessage.addListener(function(request, sender, sendResponse) {
  if(request.cmd == "createSelectionMenu") {
    sendResponse({cmd: "saveText"}); //Do things
  }
});

Content_script.js

chrome.extension.sendMessage({ cmd: "createSelectionMenu", data: selectedText },
  function(response) {
    if(response.cmd == "saveText") { 
      createForm();
    }
  }
});

解决方案

What I do is following:

I keep track of my opened tabs

content script:

// connect to the background script
var port = chrome.extension.connect();

background script

// a tab requests connection to the background script
chrome.extension.onConnect.addListener(function(port) {
  var tabId = port.sender.tab.id;
  console.log('Received request from content script', port);

  // add tab when opened
  if (channelTabs.indexOf(tabId) == -1) {
    channelTabs.push(tabId);
  }

  // remove when closed/directed to another url
  port.onDisconnect.addListener(function() {
    channelTabs.splice(channelTabs.indexOf(tabId), 1);
  });
});

Now I can notify all my registered tabs (i.e. content scripts) from my background script when a certain action happened:

var notification = { foo: 'bar' };
for(var i = 0, len = channelTabs.length; i < len; i++) {
  chrome.tabs.sendMessage(channelTabs[i], notification, function(responseMessage) {
    // message coming back from content script
    console.log(responseMessage);
  });
}

And again, on the other side in the content script, you can add a listener on these messages:

chrome.extension.onMessage.addListener(function(request, sender, sendResponse) {
  if (request.foo == 'bar') {
    executeStuff();
    // if a callback is given:
    sendResponse && sendResponse('success');
  }
});

It's a bit of a brainf*ck, because it's redundant at some places. But I like it best that way, because you can wrap it and make it a bit easier.

If you want to see how I am using this, see my repository on GitHub: chrome-extension-communicator.

这篇关于如果从后台发送响应,则在内容脚本中执行一个函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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