从弹出窗口到 content.js 的 sendMessage 在 chrome 扩展中不起作用

编程入门 行业动态 更新时间:2024-10-27 20:35:45
本文介绍了从弹出窗口到 content.js 的 sendMessage 在 chrome 扩展中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试为 chrome 扩展制作弹出界面.我似乎无法从 popup.html/popup.js 向 content.js 脚本发送消息.这是我到目前为止所拥有的.当我单击扩展图标时,我会看到一个显示 clickme 的按钮.我单击它并没有任何反应,chrome javascript 控制台中没有错误,也没有给 content.js 的消息.

I'm trying to make a popup interface for a chrome extension. I can't seem to send a message from the popup.html/popup.js to the content.js script. Here's what I have so far. When I click on the extension icon I get a button that says clickme. I click it and nothing happens, no errors in the chrome javascript console, and no message to content.js.

清单

{ "content_security_policy": "script-src 'self' 'unsafe-eval'; object-src 'self'", "manifest_version": 2, "name": "extensiontest", "version": "0.2", "content_scripts": [ { "matches": [ "<all_urls>" ], "js": ["content.js"] } ], "browser_action": { "default_icon": "Beaker.png", "default_popup":"popup.html" }, "background": { "scripts": ["background.js"] }, "permissions": [ "tabs" ] }

popup.html

<html> <head></head> <script src="popup.js"></script> <body> <input id="button1" type=button value=clickme> </body></html>

popup.js

function popup(){ alert(1); chrome.tabs.query({active: true, currentWindow: true}, function(tabs) { var activeTab = tabs[0]; chrome.tabs.sendMessage(activeTab.id, {"message": "start"}); }); button1=document.getElementById("button1"); button1.addEventListener('click', popup) }

content.js

chrome.runtime.onMessage.addListener( function(request, sender, sendResponse) { if( request.message === "start" ) { start(); } } ); function start(){ alert("started"); }

推荐答案

我修改了你的 popup.js 并使用 DOMContentLoaded 作为 Chrome 扩展,建议如下:

I modified your popup.js and used DOMContentLoaded as Chrome extension suggested like:

popup.js:

function popup() { chrome.tabs.query({currentWindow: true, active: true}, function (tabs){ var activeTab = tabs[0]; chrome.tabs.sendMessage(activeTab.id, {"message": "start"}); }); } document.addEventListener("DOMContentLoaded", function() { document.getElementById("button1").addEventListener("click", popup); });

content.js:

chrome.runtime.onMessage.addListener( function(request, sender, sendResponse) { if( request.message === "start" ) { start(); } } ); function start(){ alert("started"); }

popup.html:

<!DOCTYPE html> <html> <head></head> <script src="popup.js"></script> <body> <input id="button1" type=button value=clickme> </body></html>

我已经测试过它可以工作.

I've tested on my end it works.

更多推荐

从弹出窗口到 content.js 的 sendMessage 在 chrome 扩展中不起作用

本文发布于:2023-08-06 04:53:54,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1310186.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:中不   弹出窗口   content   js   sendMessage

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!