I am developing an extension in google chrome.I want to show desktop notification when any new page loads in currently active tab.
But my written code is not working properly.
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo) {
if (changeInfo.status === 'complete') {
chrome.tabs.executeScript(tabId, {
chrome.notifications.create(‘id1’, {
type: ‘basic’,
iconUrl: ‘icon.png’,
title: ‘Review Baed Surfing’,
message: ‘Check URL now by clicking FAKE URL icon infront on Address Bar!’,
priority: 0
},
function() { /* Error checking goes here */}
);
});
}
});
I think you only need to call chrome.notifications.create() in background script and chrome.tabs.executeScript only accept file url or code (css, js) to inject.
And you could check the following items when the notification doesn't show as expected:
Add "notification" to permissions in manifest.json.
"permissions": ["notifications"]
Notifications API only supports Windows, Chrome OS and Mac currently.
The 'option' parameter of create function must include a notification title, message and iconUrl. The rich notification will not work properly without any error if you missed any one of them.
var opt = {
type: "basic",
title: "Primary Title",
message: "Primary message to display",
iconUrl: "url_to_small_icon"
}
Hope this is helpful.
[SOLVED]
i make following changes in code
chrome.tabs.onUpdated.addListener( function (tabId, changeInfo, tab) {
if (changeInfo.status == 'complete' && tab.active) {
chrome.notifications.create('id1',{
type: 'basic',
iconUrl: 'icon.png',
title: 'Review Baed Surfing',
message: 'Check URL now by clicking FAKE URL icon infront on Address Bar!',
priority: 0
},
function() { /* Error checking goes here */}
);
}
});
Now it works properly.
Thank You,
Related
I am new to Google Chrome Push notifications and I was just reading some questions and answers here, on stackoverflow and I have ended with this easy push notification javascript.
navigator.serviceWorker.register('sw.js');
function notify() {
Notification.requestPermission(function(result) {
if (result === 'granted') {
navigator.serviceWorker.ready.then(function(registration) {
registration.showNotification('test notification', {
body: 'Hey I am test!',
icon: 'image.png',
});
});
}
});
}
Its just simple notification, but I need open a new window with other webpage after click on notification.
I know it is possible, but I cant find examples using "serviceWorker" syntax.
Please help. Thanks.
I am guessing you are in a Service Worker context, because that's where Push Notifications are received. So you have the self object to add a event listener to, that will react to a click on the notification.
(Place this code in your sw.js file, which is your Service Worker script.)
self.addEventListener('notificationclick', function(event) {
let url = 'https://example.com/some-path/';
event.notification.close(); // Android needs explicit close.
event.waitUntil(
clients.matchAll({type: 'window'}).then( windowClients => {
// Check if there is already a window/tab open with the target URL
for (var i = 0; i < windowClients.length; i++) {
var client = windowClients[i];
// If so, just focus it.
if (client.url === url && 'focus' in client) {
return client.focus();
}
}
// If not, then open the target URL in a new window/tab.
if (clients.openWindow) {
return clients.openWindow(url);
}
})
);
});
If you want to open website with dynamic URL received from FCM push notification or any other web push notification then
BELOW IS AN EXAMPLE OF SERVICE WORKER USED FOR FCM PUSH NOTIFICATION
messaging.setBackgroundMessageHandler(function(payload) {
console.log('[firebase-messaging-sw.js] Received background message ', payload);
// Customize notification here
var notificationTitle = payload.data.title; //or payload.notification or whatever your payload is
var notificationOptions = {
body: payload.data.body,
icon: payload.data.icon,
data: { url:payload.data.click_action }, //the url which we gonna use later
actions: [{action: "open_url", title: "Read Now"}]
};
return self.registration.showNotification(notificationTitle,
notificationOptions);
});
and handle click event with below code
self.addEventListener('notificationclick', function(event) {
switch(event.action){
case 'open_url':
clients.openWindow(event.notification.data.url); //which we got from above
break;
case 'any_other_action':
clients.openWindow("https://www.example.com");
break;
}
}
, false);
Hope it helps!
(This code refers to firebase messaging) I was also searching for a soluting and the answer was very easy, but there was no doc saying it clearly. You need to put "click_action" = "your url" inside the notification json. Here is an example:
notification: {
title: "Come",
icon: '../../../../assets/logo.png',
vibrate: [300,100,400,100,400,100,400],
body: "some text",
click_action : "your link"
}
Hope it helps.
{
"notification": {
"title": "Hey there",
"body": "Subscribe to might ghost hack youtube channel",
"click_action" : "http://localhost:4200"
},
"to":"YOUR_TOKEN"
}
This worked for me
"#angular/fire": "^6.1.5",
"firebase": "^7.0 || ^8.0"
Trying to build a chrome extension with notifications, and I would like a button that displays a notification. This is the HTML code:
<div><button onclick="notifyMe()">Notify me!</button></div>
This button shows in the extension, but when I press it, nothing happens. Here is my js code:
function notifyMe() {
var notification = new Notification("Hi there!");
}
Am I missing any js code? I have no idea
Not sure if I'm following correctly but if you want to show a chrome notification there's actually the chrome notifications API
I'd do the following:
<div><button onclick="notifyMe()">Notify me!</button></div>
JS
function notifyMe() {
chrome.notifications.create('some id for this notification', {
type: 'basic', // "basic", "image", "list", or "progress"
title: 'a title for this notification',
message: 'the message you want to show'
}, function () { // called when the notification is created });
}
If you want to use the Notification you have to ask for permissions first to use it (taken from the Web Notifications article on MDN):
// At first, let's check if we have permission for notification
// If not, let's ask for it
if (window.Notification && Notification.permission !== "granted") {
Notification.requestPermission(function (status) {
if (Notification.permission !== status) {
Notification.permission = status;
}
});
}
function notifyMe() {
if (window.Notification && Notification.permission === "granted") {
var n = new Notification("Hi!");
}
}
Your code is calling the Desktop Notification API and not the Chrome Notification API:
var notification = new Notification("Hi there!");
Apparently Google modified the level of permission in chrome extension (works perfectly in Chrome 43 +). Just include this line in your manifest.json, and Desktop notifications API will work (as well as the Chrome Notification API):
"permissions": [ "notifications", ...etc... ],
Adding notifications to the permissions scopes, you can check Notification.permission returns "granted".
I'm trying to make a chrome extension for the Pinterest.
I followed the examples I found from the Chrome extension sample (the one with displaying icon in the omnibox when there is a 'g' in the url) and changed the file a bit to make it display the icon when the site has "pinterest.com" in it. Here is the code:
manifest.json:
"permissions": [
"tabs",
"http://*.pinterest.com/"
]
background.js, I copied most of the code from the example online:
function showPinterestAction(tabId, ChangeInfo, tab) {
if(tab.url.indexOf('pinterest.com') > -1){
chrome.pageAction.show(tabId);
}
/* This doesn't work. tab.url return undefine to me :( */
};
chrome.tabs.onUpdated.addListener(function(tabId, change, tab) {
if (change.status == "complete") {
showPinterestAction(tabId);
}
});
chrome.tabs.onActivated.addListener(function(tabId, info) {
selectedId = tabId;
showPinterestAction(tabId);
});
// Ensure the current selected tab is set up.
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
alert(tabs[0].id);
showPinterestAction(tabs[0].id);
});
It is not displaying the icon at the right page. If I try to alert(tab.url) it gives me undefined. Can someone please tell me what's wrong with my code?
Well, you're only ever calling showPinterestAction with one parameter, tabId.
No surprises, therefore, that tab parameter is simply undefined. The signature of showPinterestAction follows the tab update callback, but you're not using it like one.
You can modify showPinterestAction to pull the data it needs:
function showPinterestAction(tabId) {
chrome.tabs.get(tabId, function(tab){
if(tab.url.indexOf('pinterest.com') > -1){
chrome.pageAction.show(tabId);
}
});
};
You also probably want to make your match pattern more general: "*://*.pinterest.com/*" should cover your use case.
Alternatively, instead of latching on to multiple tabs events, you can use declarativeContent API - it was created for this.
var rule = {
conditions: [
new chrome.declarativeContent.PageStateMatcher({
pageUrl: { hostSuffix: 'pinterest.com' }
})
],
actions: [ new chrome.declarativeContent.ShowPageAction() ]
};
chrome.runtime.onInstalled.addListener(function(details) {
chrome.declarativeContent.onPageChanged.removeRules(undefined, function() {
chrome.declarativeContent.onPageChanged.addRules([rule]);
});
});
In this case you will not need "heavy" permissions like "tabs" or host permissions. Your manifest only needs
"permissions": [
"declarativeContent",
"activeTab"
]
for this to work.
I'm developing a extension for the chrome browser and i want to add a specified contextmenu for pdf documents. I also add to specified contextmenus for the type "page" and "image".
If i set the type to "all" then there is a contextmenu, but not specified for pdf documents.
Is it possible to add a specified contextmenu for pdf documents or should i use a the type "all" an it make switch case in the clickEventHandler?!
See more at:
http://developer.chrome.com/extensions/contextMenus.html
These are the "file" types:
contexts ( optional array of enum of "all", "page", "frame", "selection", "link", "editable", "image", "video", "audio", or "launcher" )
I'm guessing that you want to add a context menu only when a PDF is shown in a tab, right? Just asking because I thought at first that you wanted to add the context menu on links to PDF files, which is indeed possible*. (as you probably know)
I couldn't find a way to do this directly, however one alternative could be to listen to chrome.tabs.onActivated and add or remove your context menu based on if the current URL matches a PDF file. One drawback is that it means asking for the tabs permission which might looks scary to users. ("This extension can access your tabs and browsing activity" or something like that)
*for the curious, you do it like this:
chrome.contextMenus.create({
title: "Hello world",
contexts: ["link"],
targetUrlPatterns: ["*://*/*.pdf"]
});
(you would add the other options that interest you of course)
This functions works for me for pdf documents:
chrome.tabs.onActivated.addListener(function (info) {
var tab = chrome.tabs.get(info.tabId, function (tab) {
if (tab.url.indexOf(".pdf") > 0) {
chrome.contextMenus.create({
"id": "1",
title: "Just for PDF Documents",
contexts: ["all"],
onclick: function (e) {
}
});
} else {
chrome.contextMenus.remove("1", null);
}
});
});
Maybe the line
if (tab.url.indexOf(".pdf") > 0) {
should edit with a expression!
Current answers are not perfect:
The way to remove context menus
Not work well with new open pdf file or multiple windows
let g_contextMenus = [{
id: "test",
title: "test"
}];
function createContextMenus() {
for (var menu of g_contextMenus) {
chrome.contextMenus.create({
id: menu["id"],
type: "normal",
title: menu["title"],
contexts: ["all"]
});
}
}
createContextMenus();
function updateContextMenu(tabId) {
chrome.tabs.get(tabId, function(tab) {
var suffix = tab.url.slice(-4);
var isPdf = suffix.toLowerCase() == ".pdf";
for (var menu of g_contextMenus) {
chrome.contextMenus.update(menu["id"], { visible: isPdf })
}
});
};
/**
* Switch tab
**/
chrome.tabs.onActivated.addListener(function(info) {
updateContextMenu(info.tabId);
});
/**
* New open file
**/
chrome.tabs.onUpdated.addListener(function(tabId, info, tab) {
var suffix = tab.url.slice(-4);
if (info.status == "complete" && suffix.toLowerCase() == ".pdf") {
updateContextMenu(tabId);
}
});
/**
* Multiple window/New window
**/
chrome.windows.onFocusChanged.addListener(function(winId) {
chrome.tabs.query({ lastFocusedWindow: true, active: true }, function(tabs) {
updateContextMenu(tabs[0].id);
});
});
References:
How to get the currently opened tab's URL in my page action popup?
Check if Item is already in the Context Menu
Working on a project that has a website and a Facebook page. They both reference the same SWF file and JS code that the SWF file uses to interact with the website/Facebook.
The custom Javascript action, which invokes the FB.ui() method for sharing, works so much in that the dialog/popup appears, however Facebook results with an error ("An error occurred. Please try again later."). I get this error in all browsers.
Using a stream.share method works fine, however the stream.publish is giving me grief on the website. What's notable is that the exact same code works within Facebook.
I am loading the FBJS SDK through the same methods on both sites (The Facebook page is an iframe that's hosted on the same server) and also loading the scripts for the pages in the same order.
function connectFacebook(score) {
// No score, share link
if ( score == 0 ) {
FB.ui({
method: 'stream.share',
u: 'http://www.example.com/'
});
// Has score, publish to wall
} else {
FB.ui({
method: 'stream.publish',
message: 'I scored '+score+' at Game!',
attachment: {
name: 'Game',
caption: 'Game caption',
description: 'I scored '+score+'! Play and share to win the prize pack!',
href: 'http://www.example.com/'
},
action_links: [
{ text: 'Game', href: 'http://www.example.com/' }
],
user_message_prompt: 'Tell your friends about Game'
},
function(response) {
if ( response && response.post_id ) {
//alert( 'Post was published.' );
} else {
//alert( 'Post wasn\'t published.' );
}
});
}
}
I found out what the error was. When connecting to the FBJS SDK on the website, I had a Page ID entered instead of an App ID.