我正在编写一个chrome扩展程序,只是在它警告Hello World我为权限指定的页面完成加载,但它不起作用,这是我的脚本
文件:manifest.json
{
"name": "Hello",
"version": "1.0",
"description": "Says hello to Google",
"permissions": ["http://*.google.com/"]
"browser_action": {
"popup": "Hello.html"
}
}
文件:Hello.html
<script language="Javascript">
alert("Hello World");
</script>
答案 0 :(得分:56)
您正在添加一个浏览器操作弹出窗口,它会在浏览器的右上角添加一个按钮。 (它可能是隐形的,因为你还没有为它指定一个图像。你的地址栏右侧应该有一些空白区域;尝试点击它以在弹出窗口中看到你的Hello.html
。)
你想要的是content script。内容脚本可以注入Chrome加载的每个页面。您可以使用清单文件中的matches
和exclude_matches
子项来指定哪些页面可以获取您注入的脚本。
{
"name": "Hello",
"version": "1.0",
"description": "Says hello to Google",
"permissions": ["tabs", "*://*.google.com/*"],
"content_scripts": [
{
"matches": ["*://*.google.com/*"],
"js": ["hello.js"]
}
]
}
确保您将Hello.html
重命名为hello.js
(并删除<script>
代码。)
另请注意,我已将您的http://*.google.com/
更改为*://*.google.com/*
,以便它将通过HTTP和HTTPS应用于Google(并且结尾*
可确保它将应用于google.com
上的所有网页{1}},而不仅仅是主页。)
答案 1 :(得分:2)
我遇到了这个答案,试图找到一种方法只启用某些页面上的图标,这就是我所做的。 Docs
背景.js
chrome.runtime.onInstalled.addListener(function() {
chrome.tabs.onActivated.addListener(async info => {
const tab = await chrome.tabs.get(info.tabId);
const isGithub = tab.url.startsWith('https://github.com/');
isGithub
? chrome.action.enable(tab.tabId)
: chrome.action.disable(tab.tabId);
});
});
确保在清单中添加 tabs 权限
答案 2 :(得分:0)
First of all there are 2 types of extensions:
1. Browser Action - which work for multiple websites or almost all websites
2. Page Action - which work for specific websites or webpages [which is needed
in our case]
Follow these steps to show your extension only on google:
Step 1: Go to manifest.json file and add the below code snippet
"background":{
"scripts":["background.js"],
"persistent":false
}
***also make sure you have page action not browser action**
"page_action" : { "default_popup":"your_popup.html" }
Step 2: Now add permissions in manifest:
"permissions":["declarativeContent"]
Step 3: Now create background.js in root folder of extension and add the
below code in it, this will let the extension to work only on
urls that contain google.com
// When the extension is installed or upgraded ...
chrome.runtime.onInstalled.addListener(function() {
// Replace all rules ...
chrome.declarativeContent.onPageChanged.removeRules(undefined,
function() {
// With a new rule ...
chrome.declarativeContent.onPageChanged.addRules([
{
// That fires when a page's URL contains a 'g' ...
conditions: [
new chrome.declarativeContent.PageStateMatcher({
pageUrl: { urlContains: 'google.com' },
})
],
// And shows the extension's page action.
actions: [ new chrome.declarativeContent.ShowPageAction() ]
}
]);
});
});
Step 4: Now reload your extension, you'll find that your extension will work
only for google.com
Hope this solved your query, If Yes, then Upvote the answer Thanks!