【问题标题】:execute a function in content script if response is sent from Background如果从后台发送响应,则在内容脚本中执行函数
【发布时间】:2012-11-13 15:53:00
【问题描述】:

对于我的 Chrome 扩展程序,我正在尝试将选定的文本发布到 PHP 网页。这个网站上的一个已解决问题 (Chrome Extension: how to capture selected text and send to a web service) 对我实现这一目标有很大帮助,但我想要一种不同的方式来发布文本。
而不是那里提到的 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"}); //Do things
  }
});

Content_script.js

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

【问题讨论】:

    标签: javascript background google-chrome-extension response content-script


    【解决方案1】:

    我所做的如下:

    我会跟踪我打开的标签页

    内容脚本

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

    后台脚本

    // 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);
      });
    });
    

    现在,当某个动作发生时,我可以从后台脚本通知我所有注册的标签(即内容脚本):

    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);
      });
    }
    

    同样,在内容脚本的另一端,您可以在这些消息上添加侦听器:

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

    这有点脑残,因为它在某些地方是多余的。但我最喜欢这样,因为你可以把它包装起来,让它更容易一些。

    如果您想了解我是如何使用它的,请查看我在 GitHub 上的存储库:chrome-extension-communicator

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-07-16
      • 1970-01-01
      • 1970-01-01
      • 2013-06-26
      • 1970-01-01
      • 2015-04-18
      • 1970-01-01
      相关资源
      最近更新 更多