# Web push do Chrome e Firefox para sites HTTP

<Aside type="caution" title="ATENÇÃO">
As instruções a seguir são **unificadas** para a configuração do Chrome e do Firefox, **EXCETO** pelo primeiro artigo, que é exclusivo para cada plataforma.
</Aside>

## Configuração

1. Selecione a opção Web push ao criar um projeto.

<img src="/web-push-notifications-chrome-firefox-web-push-for-http-websites-1.webp" alt=""/>

2\. Escolha http, insira a URL do seu site e o nome do projeto.

<img src="/web-push-notifications-chrome-firefox-web-push-for-http-websites-2.webp" alt=""/>

3\. Configure o Chrome e o Firefox com suas credenciais de projeto do FCM.

<Aside type="note">
Aprenda como obter as credenciais do FCM no [guia de configuração do Chrome e Firefox](/pt/developer/first-steps/connect-messaging-services/chrome-configuration/).
</Aside>

<img src="/web-push-notifications-chrome-firefox-web-push-for-http-websites-3.webp" alt=""/>

## Integração

**1.** Crie o arquivo **pushwoosh-web-pushes-http-sdk.js** no diretório raiz do seu site com o seguinte conteúdo:

```javascript
var pushwoosh = {
	PUSHWOOSH_APPLICATION_CODE: 'XXXX-XXXX',
	PUSHWOOSH_APPLICATION_CODE_GET_PARAMETER: 'pw_application_code',
	init: function (applicationCode) {
		this.PUSHWOOSH_APPLICATION_CODE = applicationCode;
		window.addEventListener('message', this.pwReceiveMessage, false);
	},
	tryInitUsingGetParameter: function () {
		var applicationCode = this.getQueryVariable(this.PUSHWOOSH_APPLICATION_CODE_GET_PARAMETER);
		console.log(applicationCode);
		if (applicationCode) {
			this.init(applicationCode);
		}
	},
	pwReceiveMessage: function (event) {
		if (event.data == 'allowPushNotifications') {
			localStorage.setItem('pwAllowPushNotifications', true);
		}
	},
	isBrowserChrome: function () {
		return navigator.userAgent.toLowerCase().indexOf('chrome') > -1;
	},
	isBrowserFirefox: function () {
		return navigator.userAgent.toLowerCase().indexOf('firefox') > -1;
	},
	isBrowserSafari: function () {
		return navigator.userAgent.toLowerCase().indexOf('safari') > -1 && !this.isBrowserChrome();
	},
	isBrowserSupported: function () {
		return this.isBrowserChrome() || this.isBrowserFirefox();
	},
	subscribeAtStart: function () {
		if (this.isBrowserSupported()) {
			if (null === localStorage.getItem('pwAllowPushNotifications')) {
				this.showSubscriptionWindow();
			}
		}
	},
	isSubscribedForPushNotifications: function () {
		return true == localStorage.getItem('pwAllowPushNotifications');
	},
	showSubscriptionWindow: function () {
		if (this.isBrowserSupported()) {
			var windowWidth = screen.width / 2;
			var windowHeight = screen.height / 2;

			var windowLeft = screen.width / 2 - windowWidth / 2;
			var windowRight = screen.height / 2 - windowHeight / 2;

			var URL = 'https://' + this.PUSHWOOSH_APPLICATION_CODE + '.chrome.pushwoosh.com/';
			var pwSubscribeWindow = window.open(URL, '_blank', 'width=' + windowWidth + ',height=' + windowHeight + ',resizable=yes,scrollbars=yes,status=yes,left=' + windowLeft + ',top=' + windowRight);
		}
	},
	getQueryVariable: function (variable) {
		// document.currentScript won't work if this code is called from function in event lister
		if (document.currentScript) {
			var urlParts = document.currentScript.src.split('?');
			if (typeof urlParts[1] !== 'undefined') {
				var vars = urlParts[1].split('&');
				for (var i = 0; i < vars.length; i++) {
					var pair = vars[i].split('=');
					if (pair[0] == variable) {
						return pair[1];
					}
				}
			}
		}
		else {
			console.error('Cannot get current script address');
		}
		return null;
	}
};
pushwoosh.tryInitUsingGetParameter();
```

**2.** Inclua o arquivo anterior em seu site e inicialize-o usando o **código do aplicativo** em vez de XXXXX-XXXXX

```javascript
<!--[if !IE]><!-->
    <script src="/pushwoosh-web-pushes-http-sdk.js?pw_application_code=XXXXX-XXXXX"></script>
<!--<![endif]-->
```

**3.** Para criar um botão de Inscrição Push, use o seguinte:

```txt
<button onclick="pushwoosh.showSubscriptionWindow()">Subscribe to push notifications</button>
```

**4.** Alternativamente, se você quiser que as Inscrições de Notificação apareçam automaticamente (em oposição ao item 4 acima), use o seguinte:

```javascript
<script>pushwoosh.subscribeAtStart();</script>
```

<Aside type="note">
#### IMPORTANTE

Uma janela pop-up só é permitida com a permissão do usuário devido à política de segurança do navegador: os bloqueadores de pop-up são ativados automaticamente sem uma ação direta do usuário. \
O navegador bloqueará os pop-ups automaticamente até que você os permita explicitamente com o clique de um botão.\
O botão de Inscrição Push mencionado acima funcionará perfeitamente sem permissões adicionais do usuário.
</Aside>

<img src="/web-push-notifications-chrome-firefox-web-push-for-http-websites-4.webp" alt=""/>

<img src="/web-push-notifications-chrome-firefox-web-push-for-http-websites-5.webp" alt=""/>

Como resultado, o usuário será solicitado a se inscrever para receber notificações push do site:

<img src="/web-push-notifications-chrome-firefox-web-push-for-http-websites-6.webp" alt=""/>