Google chrome. Send message from url notification window to page - google-chrome

I need send message on page from notification window.
How to do it
I have following page
var shownotif=0;
Set notification permissions for this page Show HTML Notification /* * Common code */ document.querySelector('#request_permission').addEventListener('click', function() {
window.webkitNotifications.requestPermission(); }, false);
// see the HTML section to see the button var url = 'index212.html'; document.querySelector('#show_html_notification').addEventListener('click', function() {
if (window.webkitNotifications.checkPermission() == 0) {
// you can pass any url as a parameter
notif=window.webkitNotifications.createHTMLNotification(url);
notif.addEventListener('display', function() {
///alert(111);
// notif.cancel();
}
);
notif.addEventListener('click', function(g, g2) {
setTimeout("tkfnm",1000);
alert(jQuery.cookie("ca2"));
// notif.cancel();
}
);
notif.show(); // note the show()
} else {
alert("This page doesn't have permission to show notifications yet.");
} }, false);
I want to be that when user click in notification window, on "parent" send my message with my information.

Related

Transform Google apps script webapp into progressive wa

i want to get more accessible my webabb deployed on Google Apps Script.
I tried to do this adding an embedded manifest:
<link rel="manifest" href='data:application/manifest+json,
{
"name":"SharePoint Title",
"short_name":"SP Title",
"description":"description",
"start_url":"get_script_url",
"icons":[
{
"src":"icon_url",
"sizes":"144x144","type":"image/png"
}
],
"background":"rgb(255,0,0)",
"theme_color":"rgb(255,255,255)",
"display":"fullscreen"
}'>
and this js code (as shown in https://developer.mozilla.org/:
let deferredPrompt;
const addBtn = document.querySelector('.add-button');
addBtn.style.display = 'none';
window.addEventListener('beforeinstallprompt', (e) => {
// Prevent Chrome 67 and earlier from automatically showing the prompt
e.preventDefault();
// Stash the event so it can be triggered later.
deferredPrompt = e;
// Update UI to notify the user they can add to home screen
addBtn.style.display = 'block';
addBtn.addEventListener('click', (e) => {
// hide our user interface that shows our A2HS button
addBtn.style.display = 'none';
// Show the prompt
deferredPrompt.prompt();
// Wait for the user to respond to the prompt
deferredPrompt.userChoice.then((choiceResult) => {
if (choiceResult.outcome === 'accepted') {
console.log('User accepted the A2HS prompt');
} else {
console.log('User dismissed the A2HS prompt');
}
deferredPrompt = null;
});
});
});
But when I can't load the page from any mobile device: Google returns an error.
Does somebody know how could I solve the problem?
Thanks a lot

Chrome extension create new tab and send message from popup.js to content script of new tab

I am developing a chrome extension where my popup.js receives a message from a content script on the current page and creates an array. Then on a button press, popup.js creates a new tab (which has a content script running) and sends that content script a message containing the array.
My popup.js:
//this message is sent from a different content script (for current page), not shown here
chrome.runtime.onMessage.addListener(function(request, sender) {
if (request.action === "getSource") {
var arr = JSON.parse(request.source);
//create new tab
chrome.tabs.create({url: "newtab.html"}, function(tab){
//send message to new tab
chrome.tabs.sendMessage(tab.id{
action: "getDataArray",
source: JSON.stringify(arr)
});
}
});
newtab-contentscript.js:
$(document).ready( function() {
chrome.runtime.onMessage.addListener(function(request, sender) {
if (request.action === "getDataArray") {
$("#result").html(JSON.parse(request.source));
}
});
newtab.html:
<script src="newtab-contentscript.js"></script>
Problem: The newtab-contentscript.js never seems to receive the message.
Are the any mistakes with how I am creating a tab or sending the message. Do you have any suggestions to how to fix this issue?
As we discussed in the comments, I guess maybe $(document).ready is too late to receive messages from chrome.tabs.sendMessage, you can test it by comparing timestamps of console.log inside the callback and on the first line of the new tab's content scripts, as #wOxxOm mentioned.
I just suggest moving message logic to background (event) page and starting the message passing from newtab-contentscript.js, in which you could control when to start sending the message.
A sample code
background.js
let source = null;
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
// sent from another content script, intended for saving source
if(request.action === 'putSource') {
source = request.source;
chrome.tabs.create({ url: 'newtab.html' });
}
// sent from newtab-contentscript, to get the source
if(request.action === 'getSource') {
sendResponse({ source: source });
}
});
newtab-contentscript.js
chrome.runtime.sendMessage({action: 'getSource'}, function(response) {
$('#result').html(response.source);
});

chrome service worker push notification show only when tab url of my site is closed or not active

I would like to show GCM service worker message only when there is no open chrome tab in my website or the tab is open and not selected (active).
Here is my code.
Error: chrome is not defined(…).
manifest.json
{
"name": "Webplus Express",
"short_name": "Webplus Express",
"icons": [{
"src": "https://raw.githubusercontent.com/deanhume/typography/gh-pages/icons/typography.png",
"sizes": "192x192",
"type": "image/png"
}],
"start_url": "/index.html",
"display": "standalone",
"gcm_sender_id": "298340340811",
"gcm_user_visible_only": true,
"background": {
"scripts": ["service-worker.js"]
},
"permissions": [
"gcm","tabs","activeTab"
]
}
service-worker.js
// The service worker running in background to receive the incoming
// push notifications and user clicks
self.addEventListener('push', function(event) {
// Since there is no payload data with the first version
// of push messages, we'll grab some data from
// an API and use it to populate a notification
var s_id=0;
self.registration.pushManager.getSubscription().then(function(subscription) {
if(subscription!=null){
s_id= subscription.endpoint.split("/").slice(-1);
var mURL="https://www.webplusexpress.com";
var ok=true;
chrome.tabs.getAllInWindow(undefined, function(tabs) {
for (var i = 0;i<tabs.length; i++) {
if (tabs[i].url && (tabs[i].url.indexOf(mURL)!=-1)) {
//chrome.tabs.update(tab.id, {selected: true});
if(tabs[i].highlighted){
ok=false;
}
return;
}
}
});
if (ok){
event.waitUntil(fetch('https://www.wpe.com/pushnotifyapi?s_id='+s_id).then(function(response) {
if (response.status !== 200) {
// Either show a message to the user explaining the error
// or enter a generic message and handle the
// onnotificationclick event to direct the user to a web page
console.log('Looks like there was a problem. Status Code: ' + response.status);
throw new Error();
}
// Examine the text in the response
return response.json().then(function(data) {
if (data.error || !data.notification) {
console.error('The API returned an error.', data.error);
throw new Error();
}
var title = data.notification.title;
var message = data.notification.message;
var icon = data.notification.icon;
console.log('icon received'+icon);
var notificationTag = data.notification.tag;
return self.registration.showNotification(title, {
body: message,
icon: icon,
tag: notificationTag
});
});
}).catch(function(err) {
console.error('Unable to retrieve data', err);
var title = 'An error occurred';
var message = 'We were unable to get the information for this push message';
var icon = 'https://www.webplusexpress.com/images/3web+carre.png';
var notificationTag = 'notification-error';
return self.registration.showNotification(title, {
body: message,
icon: icon,
tag: notificationTag
});
})
);
}
}
});
});
self.addEventListener('notificationclick', function(event) {
console.log('On notification click: ', event.notification.tag);
// Android doesn't close the notification when you click on it
// See: http://crbug.com/463146
event.notification.close();
// This looks to see if the current is already open and
// focuses if it is
event.waitUntil(
clients.matchAll({
type: "window"
})
.then(function(clientList) {
for (var i = 0; i < clientList.length; i++) {
var client = clientList[i];
if (client.url == '/' && 'focus' in client)
return client.focus();
}
if (clients.openWindow) {
return clients.openWindow('/');
}
})
);
});
Referring to Implementing Push Messaging for Chrome might help. It shows each step you need to complete in order to support push messaging in your web app wherein checking if service workers are supported is done before registering the service-worker.js file.
In addition to that, using Page Visibility API to detect when a webpage is visible or in focus might also help. When the user minimizes the webpage or moves to another tab, the API sends a visibilitychange event regarding the visibility of the page as done in SO post - Is there a way to detect if a browser window is not currently active?

Changing CSS/DOM of default popup page from background script

How can I modify popup page DOM from any listener from background script?
Two approaches.
1) Send a message to the popup script with instruction on how to update the view.
// background.js
chrome.runtime.sendMessage({updatePopup: true, update: "this", data: "that"});
// popup.js
chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) {
if(message.updatePopup) {
switch(message.update) {
/* ... */
case "this":
document.getElementById("this").value = message.data;
/* ... */
break;
/* ... */
}
}
});
Has an added benefit of not caring whether the popup is actually opened: the message will be sent out, and worst case no-one will act on it.
2) Obtain direct access to the window object.
// background.js
// A rare case of a synchronous API..
var windows = chrome.extension.getViews({type : "popup"});
if(windows) { // If popup is actually open
var popup = windows[0]; // This is the window object for the popup page
popup.document.getElementById("this").value = "that";
/* ... */
}

web notifications not working

I'm tring to use the web notifications API like in this example:
http://www.inserthtml.com/2013/10/notification-api/?utm_source=html5weekly&utm_medium=email
When i'm in this website, everything is working great, in the console i'm writing "Notification.permission" and gets "granted".
But if i'm trying to do the same in my website, i'm getting error about the Notification object and when i'm trying to print "Notification.permission" i've noticed that the Notification object doesn't have this property and other properties like "requestPermition".
This happening in all the browsers and they all updated to the last version.
i've tried to open console in other websites, like cnn.com for example, and inspect the Notifications object, and also there are missing properties.
Any idea why?? and how its working the website above??
thanks.
this is my code:
window.addEventListener('load', function(){
var button = document.getElementById( "notifications" );
function theNotification() {
var n = new Notification("Hi!", {
});
}
// When the button is clicked
button.addEventListener('click', function () {
// If they are not denied (i.e. default)
if (Notification && Notification.permission !== "denied") {
// Request permission
Notification.requestPermission( function( status ){
// Change based on user's decision
if (Notification.permission !== status)
Notification.permission = status;
});
}
});
$(button).click();
var socket = io.connect('http://localhost:3000', {query : "user=343"});
socket.on('notification', function (data) {
console.log( data );
if (Notification && Notification.permission === "granted") {
theNotification();
} else {
alert(data);
}
});
});