将消息从popup.js发送到payload.js

时间:2018-09-19 00:16:33

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

注意:这是我的第一次铬扩展,这是锻炼熟悉扩展的锻炼。

我正在做一个Chrome扩展程序来解析一个页面。当用户单击扩展按钮时,payload.js将执行页面解析,并在弹出窗口中选择一个选项,该选项将决定如何输出解析后的信息。

我希望他们选择一个选项之后,payload.js内部的函数将执行并评估该选项,并相应地格式化解析的信息。最后,它将包含格式化后的已解析信息的消息发送回popup.js,然后popup.js将其显示在弹出窗口内的文本框中。

我可以从payload.js到popup.js很好地通信,但似乎做不到。

这是我的代码以及我尝试过的内容

popup.js

 // Inject the payload.js script into the current tab after the popout has loaded
    window.addEventListener('load', function (evt) {
        chrome.extension.getBackgroundPage().chrome.tabs.executeScript(null, {
            file: 'payload.js'
        });;
    });

// Listen to messages from the payload.js script and write to popout.html
chrome.runtime.onMessage.addListener(function (message) {
    document.getElementById('output').textContent = message;
});

document.addEventListener('DOMContentLoaded', function() {
        var opt = document.getElementById('generate_type');
    opt.addEventListener('click', function() {
            chrome.runtime.sendMessage(opt.value); //contains value of selection
    });
});

payload.js

console.log("executed");
var parsed_info = [];
parse_info();

function parse_info()
{
  //CODE that parses page
}

function generate_html()
{
  //CODE that generates html output in var html
  chrome.runtime.sendMessage(html);
}

function generate_reddit()
{
  //CODE that generates MARKUP for reddit in var reddit
  chrome.runtime.sendMessage(reddit);
}

function eval_opt(opt)
{
  //evaluate if we should call generate_reddit or generate_html based on opt
}

chrome.runtime.onMessage.addListener(function (message) {
    alert(message);
    eval_opt(opt);
});

manifest.json

{
    "manifest_version": 2,

    "name": "Hello World",
    "description": "A simple page-scraping extension for Chrome",
    "version": "1.0",
    "author": "@Gabriel",

    "background": {
        "scripts": ["popup.js"],
        "persistent": true
    },

    "permissions": [
        "tabs",
        "http://*/",
        "https://*/"
    ],
    "browser_action": {
        "default_icon": "logo.png",
        "default_popup": "popup.html"
    }
}

0 个答案:

没有答案