I'm try to implement Push Notifications in Chrome with ServiceWorkers and GCM.
The notifications working fine, but the push function the event is null (self.addEventListener('push', function(event)).
The next is my code and working fine, received the notifications, but don't receive the data.
To register:
<script>
document.addEventListener('DOMContentLoaded', function () {
/*navigator.serviceWorker.getRegistration().then(function(r) {
r.unregister();
});*/
// document.querySelector("#enablepush").addEventListener('click', function (e) {
//if(Notification.permission !== 'granted') {
Notification.requestPermission().then(function (permission) {
if (permission === 'granted' && 'serviceWorker' in navigator) {
navigator.serviceWorker.register('myworker.js').then(initialiseState);
} else {
console.log('service worker not present');
}
});
//}
// });
//get subscription token if already subscribed
if (Notification.permission === 'granted') {
navigator.serviceWorker.ready.then(function (registration) {
registration.pushManager.getSubscription().then(function (subscription) {
getToken(subscription);
});
});
}
});
function SalirPush()
{
console.log("Si registro ha sido cancelado");
navigator.serviceWorker.getRegistration().then(function (r) {
r.unregister();
});
navigator.serviceWorker.ready.then(function (reg) {
reg.pushManager.getSubscription().then(function (subscription) {
subscription.unsubscribe().then(function (successful) {
// You've successfully unsubscribed
}).catch(function (e) {
// Unsubscription failed
})
})
});
}
function initialiseState() {
//check if notification is supported or not
if (!('showNotification' in ServiceWorkerRegistration.prototype)) {
console.warn('Notificaiton are not supported');
return;
}
//check if user has blocked push notification
if (Notification.permission === 'denied') {
console.warn('User has blocked the notification');
}
//check if push messaging is supported or not
if (!('PushManager' in window)) {
console.warn('Push messaging is not supported');
return;
}
//subscribe to GCM
navigator.serviceWorker.ready.then(function (serviceWorkerRegistration) {
//call subscribe method on serviceWorkerRegistration object
serviceWorkerRegistration.pushManager.subscribe({userVisibleOnly: true})
.then(function (subscription) {
getToken(subscription);
var met = JSON.stringify(subscription);
console.log("Mensaje", met);
}).catch(function (err) {
console.error('Error occured while subscribe(): ', err);
});
});
}
function getToken(subscription) {
console.log(subscription);
var token = subscription.endpoint.substring(40, subscription.endpoint.length);
//document.querySelector("#token").innerHTML = token;
try
{
$("#apikey").val(token);
}catch (e)
{
}
}
</script>
Next my workers.js is;
self.addEventListener('push', function(event) {
var url = "/push/json-data.php?param=(This is the event data info)";
event.waitUntil(
fetch(url).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.log('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;
return self.registration.showNotification(title, {
body: message,
icon: icon,
data: {
url: data.notification.url
}
});
});
}).catch(function(err) {
console.log('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 = 'img/design19.jpg';
var notificationTag = 'notification-error';
return self.registration.showNotification(title, {
body: message,
icon: icon,
tag: notificationTag
});
})
);
});
// The user has clicked on the notification ...
self.addEventListener('notificationclick', function(event) {
console.log(event.notification.data.url);
// 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(event.notification.data.url);
}
})
);
});
Next to send the Push Notifications, I use this PHP:
<?php
$estado=$_GET["estado"];
$idtoken=$_GET["id"];
$op=$_GET["op"];
if ($op != "")
{
sendFCM("My App","Hi to all", $idtoken,$estado);
}
function sendFCM($titulo,$mess,$id,$estado) {
echo "Recibi: $mess , $id, $estado";
$data = array('status'=> $estado,'mensaje'=>'"'.$mess.'"','titulo'=>'"'.$titulo.'"');
$url = 'https://fcm.googleapis.com/fcm/send';
$fields = array (
'to' => $id,
'notification' => array (
"body" => $mess,
"title" => $titulo,
"icon" => "myicon",
"color"=> "#0000ff",
"sound" => "default"
),
'data' => $data,
'payload' => $data
);
$fields = json_encode ( $fields );
$headers = array (
'Authorization: key=' . "MyGoogleKey",
'Content-Type: application/json'
);
$ch = curl_init ();
curl_setopt ( $ch, CURLOPT_URL, $url );
curl_setopt ( $ch, CURLOPT_POST, true );
curl_setopt ( $ch, CURLOPT_HTTPHEADER, $headers );
curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt ( $ch, CURLOPT_POSTFIELDS, $fields );
$result = curl_exec ( $ch );
curl_close ( $ch );
echo ($result);
}
?>
Thanks for your help.
use event.data.json().data in your push event:
self.addEventListener('push', function(event) {
event.waitUntil(
self.registration.pushManager.getSubscription().then(function(subscription) {
console.info(event.data.json().data);
});
);
});
Related
I would like to dynamically add an input element to a button and based on Angular Binding, bind the input to the selected object in the viewer. What I tried so far you find below. The input element is shown without any problem. However, I cannot access the generated input element, no input possible.
Any suggestions to solve that?
public loadMobileToolbar() {
/////////////////////// Facade ///////////////////////
// #ts-ignore
var button1 = new Autodesk.Viewing.UI.Button('mobile-text-button-facade');
var button2 = new Autodesk.Viewing.UI.Button('mobile-coloring');
button1.onClick = (event) => {
console.log(this.input);
$('#mobile-text-button-facade').attr('data-before', '');
$('#mobile-text-button-facade').html('<input style="z-index: 100000" class="custom-input" type="text" [(ngModel)]="input.facade" (change)="onChange($event)" spellcheck="false">');
};
button2.onClick = (event) => {
this.showValuesOfParameter('facade');
};
button2.addClass('mobile-coloring');
// #ts-ignore
button2.container.children[0].classList.add('fas', 'fa-palette');
// Button 4 Textfeld
button1.addClass('mobile-text-button-facade');
// SubToolbar
var controlGroupMobile = new Autodesk.Viewing.UI.ControlGroup('mobile-custom-toolbar');
// controlGroupERP.addControl(button3);
controlGroupMobile.addControl(button1);
controlGroupMobile.addControl(button2);
this.toolbarMobile = new Autodesk.Viewing.UI.ToolBar('my-custom-view-toolbar-mobile-facade', {
collapsible: false,
alignVertically: false
});
this.toolbarMobile.addControl(controlGroupMobile);
$(this.viewerComponent.viewer.container)[0].append(this.toolbarMobile.container);
$('#mobile-text-button-facade').attr('data-before', 'Facade');
}
Adding the <input> without Angular bindings seems to be working fine:
You might need to ask around in the Angular community about the bindings.
var filterbox = new Autodesk.Viewing.UI.Filterbox('mobile-filterbox', { filterFunction: this.testing });
var controlGroupMobileInput = new Autodesk.Viewing.UI.ControlGroup('mobile-custom-toolbar-input');
controlGroupMobileInput.addControl(filterbox);
buttonFilter.onClick = (event) => {
if (!this.input.objectPath && this.viewerComponent.viewer.getSelectionCount() === 0) {
$('.filter-box.docking-panel-delimiter-shadow').val('');
button1.setState(1);
button7.setState(1);
// tslint:disable-next-line: no-use-before-declare
button3.setState(1);
// tslint:disable-next-line: no-use-before-declare
button9.setState(1);
// tslint:disable-next-line: no-use-before-declare
button5.setState(1);
$('#mobile-custom-toolbar-input').hide();
this.whichInput = '';
}
else if (this.viewerComponent.viewer.getSelectionCount() > 1 && this.redSelectedDbIDs.length === 0) {
this.multiSelectedMobileInput.forEach(input => {
if (this.whichInput === 'u' || this.whichInput === 'v') {
input[this.whichInput] = Number($('.filter-box.docking-panel-delimiter-shadow').val());
}
else if (this.whichInput === 'additionalParameter') {
input[this.whichInput][0].value = $('.filter-box.docking-panel-delimiter-shadow').val();
}
else {
input[this.whichInput] = $('.filter-box.docking-panel-delimiter-shadow').val();
}
});
this.api.saveMultipleInput(this.multiSelectedMobileInput).then(
res => {
if (res === null) {
this.messageService.add({ key: 'warning', severity: 'error', summary: 'Error', detail: 'Something went wrong with SAVING' });
}
else {
this.api.getAllInputs(this.platform.currentProject._id).then(
inputs => {
this.inputs = inputs;
// #ts-ignore
this.messageService.add({ key: 'warning', severity: 'success', summary: 'Success', detail: res.modified + ' INPUT was UPDATED', life: 5000 });
this.viewerComponent.viewer.clearThemingColors(this.viewerComponent.viewer.model);
this.editTable = false;
this.unsavedChanged = false;
}
);
}
}
);
this.multiSelectedMobileInput = new Array();
this.viewerComponent.viewer.clearSelection();
$('.filter-box.docking-panel-delimiter-shadow').val('');
button1.setState(1);
button7.setState(1);
// tslint:disable-next-line: no-use-before-declare
button3.setState(1);
// tslint:disable-next-line: no-use-before-declare
button9.setState(1);
// tslint:disable-next-line: no-use-before-declare
button5.setState(1);
$('#mobile-custom-toolbar-input').hide();
this.whichInput = '';
}
else if (this.redSelectedDbIDs.length !== 0) {
this.redSelectedDbIDs.forEach(dbId => {
this.viewerComponent.viewer.model.getProperties(dbId, (r) => {
var tempInput = this.inputs.find(ele => {
if (ele.objectPath.indexOf('/')) {
return ele.objectPath.split('/')[ele.objectPath.split('/').length - 1] === r.name;
}
else {
return ele.objectPath === r.name;
}
});
this.multiSelectedMobileInput.push(tempInput);
});
});
setTimeout(() => {
this.multiSelectedMobileInput.forEach(input => {
if (this.whichInput === 'u' || this.whichInput === 'v') {
input[this.whichInput] = Number($('.filter-box.docking-panel-delimiter-shadow').val());
}
else if (this.whichInput === 'additionalParameter') {
input[this.whichInput][0].value = $('.filter-box.docking-panel-delimiter-shadow').val();
}
else {
input[this.whichInput] = $('.filter-box.docking-panel-delimiter-shadow').val();
}
});
this.api.saveMultipleInput(this.multiSelectedMobileInput).then(
res => {
if (res === null) {
this.messageService.add({ key: 'warning', severity: 'error', summary: 'Error', detail: 'Something went wrong with SAVING' });
}
else {
this.api.getAllInputs(this.platform.currentProject._id).then(
inputs => {
this.inputs = inputs;
// #ts-ignore
this.messageService.add({ key: 'warning', severity: 'success', summary: 'Success', detail: res.modified + ' INPUT was UPDATED', life: 5000 });
this.viewerComponent.viewer.clearThemingColors(this.viewerComponent.viewer.model);
this.editTable = false;
this.unsavedChanged = false;
}
);
}
}
);
I am trying to create an extension that, in the background script, opens a specified URL, and then sends a message to said tab that was opened in the content script side, but I am getting an error and I'm not sure where I'm going wrong.
Unchecked runtime.lastError: Could not establish connection. Receiving end does not exist.
background.js
let targetTab = "http://google.com"
main();
function main() {
let active = true;
let tabId = null;
let tabUrl = null;
if (active) {
chrome.tabs.create({
url: targetTab,
}, (tab) => {
console.log("Tab ID Generated: " + tab.id);
tabId = tab.id;
chrome.tabs.query({}, function (tabs) {
tabs.forEach(tab => {
console.log(tab.url);
if (tab.url !== targetTab) {
chrome.tabs.remove(tab.id);
}
})
console.log("Tab ID Sent: " + tabId);
chrome.tabs.sendMessage(tabId, {
tabId,
tabUrl,
}, (response) => {
console.log(JSON.stringify(response));
})
})
})
}
}
content.js
chrome.runtime.onMessage.addListener(
(request, sender, sendResponse) => {
if (chrome.runtime.lastError) {
console.log(chrome.runtime.lastError);
}
console.log("Got Message");
sendResponse({message: "hi to you"});
});
I want to add shoping cart under single product page (below add to cart button) how I can do this in Magento 1.9?
Use the following code to solve your query:
open: template\catalog\product\view.phtml
Find:
productAddToCartForm.submit = function(button, url) {
if (this.validator.validate()) {
var form = this.form;
var oldUrl = form.action;
if (url) {
form.action = url;
}
var e = null;
try {
this.form.submit();
} catch (e) {
}
this.form.action = oldUrl;
if (e) {
throw e;
}
if (button && button != 'undefined') {
button.disabled = true;
}
}
}.bind(productAddToCartForm);
Replace with :
productAddToCartForm.submit = function(button, url) {
if (this.validator.validate()) {
var form = this.form;
var oldUrl = form.action;
if (url) {
form.action = url;
}
var e = null;
//Start of our new ajax code
if(!url){
url = jQuery('#product_addtocart_form').attr('action');
}
var data = jQuery('#product_addtocart_form').serialize();
data += '&isAjax=1';
jQuery('#ajax_loader').show();
try {
jQuery.ajax({
url: url,
dataType: 'json',
type : 'post',
data: data,
success: function(data){
jQuery('#ajax_loader').hide();
alert(data.status + ": " + data.message);
}
});
} catch (e) {
}
//End of our new ajax code
this.form.action = oldUrl;
if (e) {
throw e;
}
}
}.bind(productAddToCartForm);
Open : catalog/product/view/addtocart.phtml
Find :
" class="button btn-cart" onclick="productAddToCartForm.submit(this)">
Replace with :
" class="button btn-cart" onclick="productAddToCartForm.submit(this)">
getSkinUrl('images/opc-ajax-loader.gif')?>'/>
Open: app\code\core\Mage\Checkout\controllers\CartController.php
Find : $params = $this->getRequest()->getParams(); in addAction() function
After the above line, place this code :
if($params['isAjax'] == 1){
$response = array();
try {
if (isset($params['qty'])) {
$filter = new Zend_Filter_LocalizedToNormalized(
array('locale' => Mage::app()->getLocale()->getLocaleCode())
);
$params['qty'] = $filter->filter($params['qty']);
}
$product = $this->_initProduct();
$related = $this->getRequest()->getParam('related_product');
/**
* Check product availability
*/
if (!$product) {
$response['status'] = 'ERROR';
$response['message'] = $this->__('Unable to find Product ID');
}
$cart->addProduct($product, $params);
if (!empty($related)) {
$cart->addProductsByIds(explode(',', $related));
}
$cart->save();
$this->_getSession()->setCartWasUpdated(true);
/**
* #todo remove wishlist observer processAddToCart
*/
Mage::dispatchEvent('checkout_cart_add_product_complete',
array('product' => $product, 'request' => $this->getRequest(), 'response' => $this->getResponse())
);
if (!$this->_getSession()->getNoCartRedirect(true)) {
if (!$cart->getQuote()->getHasError()){
$message = $this->__('%s was added to your shopping cart.', Mage::helper('core')->htmlEscape($product->getName()));
$response['status'] = 'SUCCESS';
$response['message'] = $message;
}
}
} catch (Mage_Core_Exception $e) {
$msg = "";
if ($this->_getSession()->getUseNotice(true)) {
$msg = $e->getMessage();
} else {
$messages = array_unique(explode("\n", $e->getMessage()));
foreach ($messages as $message) {
$msg .= $message.'<br/>';
}
}
$response['status'] = 'ERROR';
$response['message'] = $msg;
} catch (Exception $e) {
$response['status'] = 'ERROR';
$response['message'] = $this->__('Cannot add the item to shopping cart.');
Mage::logException($e);
}
$this->getResponse()->setBody(Mage::helper('core')->jsonEncode($response));
return;
}
I want to handle user registration via ajax call. So therefore I've created a registration class (defined as a service) which will be loaded in different controllers:
public function loadRegisterForm($request)
{
$user = new User();
$form = $this->createForm(RegistrationType::class, $user, array('attr' => array('class' => 'ajaxRegisterForm',)));
$form->handleRequest($request);
$errors = "";
$parametersArray['result'] = "";
if ($form->isSubmitted())
{
if ($form->isValid())
{
$password = $this->get('security.password_encoder')
->encodePassword($user, $user->getPlainPassword());
$user->setPassword($password);
$user->setIsActive(1);
$user->setLastname('none');
$em = $this->getDoctrine()->getManager();
$em->persist($user);
$em->flush();
$parametersArray['result'] = new JsonResponse(
array(
'message' => 'Success! User registered!',
'result' => $this->renderView('ImmoBundle::security/successlogin.html.twig')
), 400);
}
else
{
$errors = $this->get('validator')->validate($form);
$parametersArray['result'] = new JsonResponse(
array(
'message' => 'Failure! User not registered!',
'result' => $this->renderView('ImmoBundle::security/successlogin.html.twig'),
'errors' => $errors,
), 200);
}
}
$parametersArray['register_form'] = $form;
$parametersArray['errors'] = $errors;
return $parametersArray;
}
Then I've created a main controller, where registration form is being loaded:
/*
* #Route("/", name="MainPageNotPaginated")
*/
public function indexAction(Request $request)
{
/**
* Load register form
*/
$registerForm = $this->get('register_form_service');
$registerFormParameters = $registerForm->loadRegisterForm($request);
return $this->render(
'ImmoBundle::Pages/mainPage.html.twig',
array(
'register_form' => $registerFormParameters['register_form']->createView(),
'errors' => $registerFormParameters['errors'],
'result' => $registerFormParameters['result'],
)
);
}
Further I've added an ajax call to my javascript file:
$('.registerFormContainer').on('submit', '.ajaxRegisterForm', function (e) {
e.preventDefault();
$.ajax({
type: $(this).attr('method'),
url: $(this).attr('action'),
data: $(this).serialize()
})
.done(function (data) {
if (typeof data.message !== 'undefined') {
$('.registerFormContainer').html(data.result);
}
alert('success');
})
.fail(function (jqXHR, textStatus, errorThrown) {
if (typeof jqXHR.responseJSON !== 'undefined') {
$('.registerFormError').html(jqXHR.responseJSON.result);
} else {
alert("fail");
}
});
});
Now, when I submit the registration form without filling in data (which normally should return an error) I've got an 'success' alert. The same 'success' alert is visible when the submitted registration form is valid.
I've tried
console.log(data.message)
but console says 'undefined'.
What am I doing wrong here?
Ok, I've figured it out. I've just added this line to my main controller (not the service one):
if ( $request->isXmlHttpRequest() ) {
return $registerFormParameters['result'];
}
I have here in my php file (laravel ) after i send an email and get a response to the mobile application
$msg ="email sent " ; $erreur=false ;
return response()->json(['Message' => $msg, 'erreur' => $erreur]);
But, When I get a response using this code in my javascript file
sendButton.onload = function(e)
{
Ti.API.debug(this.responseText);
var json = this.responseText;
var response = JSON.parse(json);
if (response.erreur == false)
{
alert("a Password has been send to you email ");
}
else
{
alert(response.Message);
}
};
I get this error
The error is pretty straight forward the response is null
sendButton.onload = function(e)
{
Ti.API.debug(this.responseText);
var json = this.responseText;
var response = JSON.parse(json);
if (response !=null && response.erreur == false)
{
alert("A password has been sent to your email.");
}
else
{
console.log(response); //probably doesnt have Message either
}
};
#MikeMiller
here is my Js code that communicates with my API
loginBtn.addEventListener('click',function(e)
{
if ( email.value!='')
{
try {
loginReq.open("POST","http://192.168.0.105/appcelerator/public/");//my local ip im testing on my computer
var params = {
email:email.value,
};
loginReq.send(params);
}catch (e)
{
alert(e.message);
}
}
else
{
alert("All fields are required");
}
});
now here is my code in my API (php laravel )
public function getPassword(Request $request)
{
$email = $request["email"];
$user = \DB::table('users')
->where('email', $request['email'])
->first();
$email = $user->email;
session()->put('email',$email);
if (!$user)
{
$msg = 'invalid email adresses';
$erreur = true ;
}else
{
Mail::send('emails.test',['password' => $this->generatePass() ],function($message )
{
$message->to(session()->get('email'),'Bonjour')->subject('welcome:');
});
$msg = 'Password has benn send to your email ';
$erreur = false;
}
return response()->json(['Message' => $msg, 'erreur' => $erreur]);
}
when it's executed i get the email in my email adresse but the response as you know is null. that's my problem