【问题标题】:No action in passing simple message from popup.html to background.js将简单消息从 popup.html 传递到 background.js 没有任何动作
【发布时间】:2013-08-14 18:35:07
【问题描述】:

我是 chrome 扩展编码的新手,对 javascript 比较陌生。扩展的类型是 page_action 。我正在尝试通过单击 popup.html 中的按钮向 background.js 发送一条简单的消息。我在这个网站上看到过类似的问题,但似乎没有任何效果。扩展的加载很好。请帮忙

/* __background.js__  */

function checkForValidUrl(tabId, changeInfo,tab){
console.log("Extension loaded");
chrome.pageAction.show(tabId);
}

function readMessage (request, sender, sendResponse){
alert("reached");
console.log(request.greeting);
sendRequest({farewell:"goodbye"});
}

chrome.extension.onRequest.addListener(readMessage);
chrome.tabs.onUpdated.addListener(checkForValidUrl);


 /* __manifest.json__  */
{
"name": "DemoExtension",
"version": "1.0",
"manifest_version": 2,
"background": {
    "scripts": [
    "jquery.js",
    "background.js"
    ]
},

"description": "demo extension to learn coding chrome extensions.",
"icons": {
    "16": "images/16x16.png",
    "48": "images/48x48.png",
    "128": "images/128x128.png"
},

"page_action": {
    "default_icon": {
        "19": "images/19x19.png",
        "38": "images/38x38.png"
    },
    "default_title": "Demo extension",
    "default_popup": "popup.html"
},

"options_page": "options.html",

"permissions": [
    "tabs",
    "storage",
    "http://*/*",
    "https://*/*"
]   
 }

-

__popup.html__
<!DOCTYPE HTML>
<html>
<head>
    <title>Demo extension</title>
    <script src="./popup.js"></script>
</head>
<body>
    <button id="clickMe">Add</button>   
</body>
</html>

-

__popup.js__
function sendMessageToExtn() {
alert("reached in popup");
chrome.extension.sendMessage({
    greeting : "hello" }, 
            function(response) { console.log(response.farewell);
});
}

document.getElementById('clickMe').addEventListener('click', function () {
sendMessageToExtn();

});

我现在收到错误未捕获的类型错误:无法调用 null 的方法 'addEventListener'(匿名函数)

有一个类似的question

【问题讨论】:

  • 现代扩展中禁止popup.html 中的内联&lt;script&gt;。将你的 JS 代码移动到它自己的文件中,并用 &lt;script src="..."&gt; 标签包含它。
  • @apsillers 我已经添加了 manifest.json。我认为不存在端口错误。请自行确认。我会将脚本从 popup.html 删除到外部文件,然后重试。谢谢
  • 我提供了该副本,因为您犯了同样的错误(HTML 中的内联脚本),可以以同样的方式修复,即使该错误给您带来的问题与它造成的问题不同其他人。
  • @apsillers 我已将脚本移至外部 js 文件,但我现在在调试器中出现以下错误。 拒绝执行内联事件处理程序,因为它违反了以下内容安全策略指令:“script-src 'self' chrome-extension-resource:” popup.html &lt;!DOCTYPE HTML&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;Add item to CreateYourLook&lt;/title&gt; &lt;script src="./popup.js" type="text/javascript" charset="utf-8"&gt;&lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;button id="submit" onclick="sendMessage()"&gt;Submit&lt;/button&gt; &lt;/body&gt; &lt;/html&gt;

标签: javascript google-chrome-extension


【解决方案1】:

解决了这个问题。首先结合@apsillers 的建议。然后最后通过移动

<script src="./popup.js"></script>

在正文中从头部开始,在按钮标签下方。

【讨论】:

    猜你喜欢
    • 2012-08-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-21
    • 2015-10-02
    • 2018-03-27
    • 2018-11-21
    • 1970-01-01
    相关资源
    最近更新 更多