2017-07-19 127 views
2

我想通过浏览器操作按钮打开它时更新popup.html中的html。 popup.js应向当前选项卡上运行的内容脚本发送消息,并应接收响应并更新html。但内容脚本不会收到任何消息,因此不会发送正确的响应。将邮件从弹出窗口发送到内容脚本 - Chrome扩展程序

Content.js

var text = "hello"; 
chrome.runtime.onMessage.addListener(
    function(message, sender, sendResponse) { 
     switch(message.type) { 
      case "getText": 
       sendResponse(text); 
      break; 
     } 
    } 
); 

Popup.js

chrome.tabs.getCurrent(function(tab){ 
    chrome.tabs.sendMessage(tab.id, {type:"getText"}, function(response){ 
     alert(response) 
     $("#text").text(response); 
    }); 
}); 

的manifest.json

{ 
    "manifest_version": 2, 
    "name": "It's Just A Name", 
    "description": "This extension is able to", 
    "version": "1.0", 
    "permissions" : ["tabs"], 
    "browser_action": { 
    "default_icon": "icon.png", 
    "default_popup": "popup.html", 
    "default_title": "Click here!" 
    }, 
    "content_scripts": [ 
    { 
    "matches": ["https://*/*"], 
    "js": ["jquery.min.js","content.js"] 
    }] 
} 

Popup.html

<!doctype html> 
<html> 
    <head> 
     <title>Title</title> 
     <style> 
      body { 
       font-family: "Segoe UI", "Lucida Grande", Tahoma, sans-serif; 
       font-size: 100%; 
      } 
      #status { 
       white-space: pre; 
       text-overflow: ellipsis; 
       overflow: hidden; 
       max-width: 400px; 
      } 
     </style> 
     <script src="popup.js"></script> 
    </head> 
    <body> 
     <p id="text"></p> 
    </body> 
</html> 
+0

tabs.getCurrent是不是你认为它是。使用tabs.query。首次使用方法之前,始终检查API文档。另请注意,重新加载扩展程序时,内容脚本不会自动注入。 – wOxxOm

回答

4

chrome.tabs.getCurrent用来:

获取的标签,这个脚本调用正在从

popup.js做出应该是:

chrome.tabs.query({active: true, currentWindow: true}, function(tabs) { 
    chrome.tabs.sendMessage(tabs[0].id, {type:"getText"}, function(response){ 
     alert(response) 
     $("#text").text(response); 
    }); 
}); 
+1

你需要它成为'chrome.tabs.query({active:true,currentWindow:true} ...'。你需要指定'currentWindow:true'来限制只显示当前窗口的结果。那么当用户打开多个窗口时(即有时'tabs [0]'将成为当前窗口中的活动选项卡,有时它会成为其他窗口中的活动选项卡),则会出现间歇性问题。 – Makyen

+0

@Makyen,正确,谢谢 – Deliaz

+0

@Deliaz如何从content.js发送消息/数据到popup.js?plz help –

0

要添加到上面的答案,你经常想发送一个味精从弹出到所有标签,所以

弹出:

chrome.tabs.query({}, tabs => { 
    tabs.forEach(tab => { 
    chrome.tabs.sendMessage(tab.id, msgObj); 
    }); 
}); 

内容脚本:

chrome.runtime.onMessage.addListener(msgObj => { 
    // do something with msgObj 
}); 
相关问题