2

重现问题的步骤

a) 使用以下所有代码准备一个扩展

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

c) 点击“热门问题:标题在此处输入图像描述

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

清单文件

  {
  "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/" ]
        }]
  }

编辑器.html 文件

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

编辑器.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;

有什么建议么??

4

1 回答 1

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/" ]
        }]
  }

编辑器.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

;

于 2012-11-19T12:21:37.327 回答