【问题标题】:How to pass the result of asynchronous operation from injected content script?如何从注入的内容脚本传递异步操作的结果?
【发布时间】:2015-12-03 19:59:47
【问题描述】:

我的 Chrome 扩展程序通过注入此内容脚本成功地在活动页面(非跨域)上执行 AJAX 请求:

// post.js
$.post("/login", {
    name: "blabla"
}, function (data) {
    alert("Success!");
});

这个脚本是从弹出/背景页面注入chrome.tabs.executeScript

chrome.tabs.executeScript(null, {
    file: '/src/assets/jquery-2.1.4.min.js'
}, function () {
    chrome.tabs.executeScript({
        file: 'post.js'
    });
});

如何将此 AJAX 请求的结果传递回我的弹出页面或后台页面?

【问题讨论】:

  • 非常感谢!正在工作!
  • @wOxxOm 认为您可以编辑这个问题并回答它吗?我认为不用将副本固定在上面就可以了。

标签: javascript ajax google-chrome google-chrome-extension


【解决方案1】:

Send a message来自内容脚本中的回调函数:

$.post("/login", {
    name: "blabla"
}, function (data) {
    chrome.runtime.sendMessage({results: data});
});

或者发送消息并从弹出/后台页面接收响应:

    chrome.runtime.sendMessage({results: data}, function(response) {
        console.log(response);
    });

并在弹出/背景页面中声明将处理消息的侦听器:

chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) {
    if (message.results) {
        console.log('Got data, tab #%d', sender.tab ? sender.tab.id : -1, message.results);
        sendResponse({reply: "thanks"}); // optional, not required
    }
});

注意事项:

  • 只能传递 JSON 可序列化对象,因此您不能使用 $.post$.ajaxdataType: 'xml' 参数,因为这种情况下的响应是不可序列化的 Document。请改用 dataType: 'html' 并在侦听器中接收时将其转换为 Document
  • 从扩展工具栏弹出窗口注入内容脚本时,请注意弹出窗口可能会被用户关闭,因此其事件侦听器将被破坏并且消息将丢失。使用后台页面接收消息时,这不是问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多