端口错误:无法建立连接。接收端不存在

时间:2012-11-17 16:44:21

标签: google-chrome-extension

重现问题的步骤

a)准备一份包含以下所有代码的扩展程序

b)转到https://stackoverflow.com/

c)点击“热门问题:标题enter image description here

您将收到错误消息“端口错误:无法建立连接。接收端不存在”

清单文件

  {
  "name": "Demo",
  "version": "1.0",
  "manifest_version": 2,
  "description": "This is a demo",

  "content_scripts": [ {
        "all_frames": true,
        "js": ["contentscript1.js" ],
        "matches": [ "https://stackoverflow.com/" ]
        }]
  }

Editor.html文件

<html>
<head>
<script src="editor.js"></script>
</head>
<body>
<div id="content"></div> 
</body>
</html>

Editor.js文件

function onRequest(message,sender,call){ 
     document.getElementById("content").value = message; 
}
 chrome.extension.onMessage.addListener(onRequest);

contentscript1.js

function bindevent(){ 
window.open(chrome.extension.getURL("editor.html"),"_blank","toolbar=no, titlebar=no,location=no, directories=no, status=no, menubar=no, scrollbars=yes, resizable=yes, copyhistory=yes, width=720, height=400");
    message = "Sample Message"; 
    chrome.extension.sendMessage(message,function (res){}); 

}; 

document.getElementById('h-top-questions').onclick=bindevent;

有什么建议吗?

1 个答案:

答案 0 :(得分:1)

我正在加载子窗口/扩展页面时发送消息;我在完全加载后发送了消息,它解决了我的问题。

最终守则

清单文件

{
  "name": "Demo",
  "version": "1.0",
  "manifest_version": 2,
  "description": "This is a demo",

  "content_scripts": [ {
        "all_frames": true,
        "js": ["contentscript1.js" ],
        "matches": [ "http://stackoverflow.com/" ]
        }]
  }

Editor.html文件

<html>
<head>
<script src="editor.js"></script>
</head>
<body>
<div id="content"></div> 
</body>
</html>

Editor.js文件

var message = window.location.hash.substring(1);

contentscript1.js

   function bindevent(){
 message = "Sample Message"; 
    window.open(chrome.extension.getURL("editor.html")+"#"+message,"_blank","toolbar=no, titlebar=no,location=no, directories=no, status=no, menubar=no, scrollbars=yes, resizable=yes, copyhistory=yes, width=720, height=400");
    }; 

document.getElementById('h-top-questions').onclick=bindevent