消息从弹出窗口传递到内容脚本

消息从弹出窗口传递到内容脚本

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

问题描述

我试图将数据从弹出窗口传递给内容脚本,但我没有任何运气。尽管我用它的方式(内容 - >弹出)反过来工作。我想要做的就是将文本输入位于弹出窗口中的输入内容,然后单击一个提交按钮,将该文本插入到网页的dom中。



这是我有:

popup.html

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

contentscript.js

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

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

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

chrome.extension.onRequest.addListener(onRequest);


解决方案

您需要指定要发送到哪个标签。像这样:

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

如果您不知道选项卡是哪个,您可以发送给所有人(可能是坏的想法)或让标签首先发送信息。



更多信息请查看此页面:。


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.

This is what I have:

popup.html

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

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扩展程序 - 消息从弹出窗口传递到内容脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-30 22:19