Chrome 扩展 - 从弹出窗口到内容脚本的消息传递 [英] Chrome Extension - Message Passing from Popup to Content Script

查看:22
本文介绍了Chrome 扩展 - 从弹出窗口到内容脚本的消息传递的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将数据从弹出窗口传递到内容脚本,但我没有任何运气.我让它以另一种方式工作(内容 - >弹出).我想要做的就是在弹出窗口中的输入中输入文本,然后单击提交按钮,该按钮会将文本插入到网页的 dom 中.

I'm trying to pass data from a popup to a content script, but I'm not having any luck. I got it to work the other way around (content -> popup) though. All I want to do is enter text into an input located in the popup and click a submit button which would insert that text into the dom of a web page.

这就是我所拥有的:

popup.html

chrome.extension.sendRequest({action:'start'}, function(response) {
    console.log('Start action sent');  
});

contentscript.js

contentscript.js

function startExtension() { console.log('Starting Extension'); }

function stopExtension() { console.log('Stopping Extension'); }

function onRequest(request, sender, sendResponse) {
    if (request.action == 'start')
        startExtension()
    else if (request.action == 'stop')
        stopExtension()
    sendResponse({});
}

chrome.extension.onRequest.addListener(onRequest);

推荐答案

您需要指定要发送到哪个选项卡.像这样:

You need to specify to which tab to send to. Like this:

chrome.tabs.sendMessage(tab.id, {action:'start'}, function(response) {
    console.log('Start action sent');
});

如果您不知道哪个是标签,您可以发送给所有人(可能是个坏主意)或让标签先发送信息.

If you don't know which is the tab, you can either send to all (probably a bad idea) or make the tab send info first.

有关更多信息,请查看此页面:消息传递.

For more information check this page: Message Passing.

这篇关于Chrome 扩展 - 从弹出窗口到内容脚本的消息传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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