javascript - Chrome 扩展 - “无法读取未定义的属性‘onMessage’”
问题描述
创建 Chrome 扩展程序。
扩展的一部分是获取当前选项卡 URL。
我发现这样做的唯一方法是将脚本放入background.js
并在其中设置一个事件侦听器script.js
除了这就是我的想法......我一直在谷歌,StackOverflow,显然一切都指向相同的答案,将脚本放入background.js
并有一个事件监听器,script.js
但我不断得到Cannot read property 'onMessage' of undefined
下面的代码不起作用,因为它获取的是 Chrome ext url,而不是当前的 tab url
current_url = window.location.href
console.log(current_url)
以下是我目前拥有的:
背景.js
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
console.log(sender.tab ?
"from a content script:" + sender.tab.url :
"from the extension");
if (request.greeting === "hello")
sendResponse({farewell: "goodbye"});
}
);
脚本.js
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
console.log(sender.tab ?
"from a content script:" + sender.tab.url :
"from the extension");
if (request.greeting === "hello")
sendResponse({farewell: "goodbye"});
}
);
manifest.js
{
"name": "Getting Started Example",
"description": "Build an Extension!",
"version": "1.0",
"manifest_version": 3,
"background": {
"service_worker": "background.js"
},
"permissions": ["storage", "activeTab", "scripting", "bookmarks", "tabs"],
"action": {
"default_popup": "popup.html",
"default_icon": {
"16": "/images/get_started16.png",
"32": "/images/get_started32.png",
"48": "/images/get_started48.png",
"128": "/images/get_started128.png"
}
},
"icons": {
"16": "/images/get_started16.png",
"32": "/images/get_started32.png",
"48": "/images/get_started48.png",
"128": "/images/get_started128.png"
},
"options_page": "options.html"
}
解决方案
推荐阅读
- c++ - 灰度图像上的 LoG 过滤器保存为二进制文件
- ruby - 如何在 ruby 中从 STDIN 读取一个非常长的字符串?
- node.js - 如何使用nodejs在特定位置写入文件?
- php - 如何使用php在字符串内的括号之间切换
- java - Docker:java:openjdk-8-jdk-alpine 图像缺少 javac 和 tools.jar
- python - 如何读取首选项,通过 geckodriver 从 Selenium Firefox webdriver 获取配置文件设置的值?
- mysql - 将行插入数据库时出现 MySQL 语法错误
- c# - 我应该使用 Oauth2 通过 Xamarin.Forms 进行 Facebook 登录身份验证,还是应该使用 Facebook SDK?
- php - 如何在博客编辑页面上显示转义的 html?
- javascript - 鼠标单击时在多个对象上选择 Fabricjs