I am using PWA to add to home screen task And I doing this in php. When I click "Add to home screen button" then script run. I made changes manifest.json according php as manifest.php. I am testing it on localhost by change https by ngrok.
I am trying to pass dynamic url in manifest file.
index.html is:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="manifest" href="manifest.php">
<link rel="icon" href="favicon.ico" type="image/gif" sizes="16x16">
</head>
<body>
<h1>Hey!!</h1>
<div class="add-to">
<button class="add-to-btn">Add to home screen</button>
</div>
<script>
if ('serviceWorker' in navigator) {
console.log("Will the service worker register?");
navigator.serviceWorker.register('service-worker.js')
.then(function(reg){
console.log("Yes, it did.");
}).catch(function(err) {
console.log("No it didn't. This happened:", err)
});
}
let deferredPrompt;
var div = document.querySelector('.add-to');
var button = document.querySelector('.add-to-btn');
//div.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;
div.style.display = 'block';
button.addEventListener('click', (e) => {
// hide our user interface that shows our A2HS button
//div.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;
});
});
});
</script>
</body>
</html>
manifest.php is:
<?php
$starturl = 'https://621b16b2b7c5.ngrok.io/add_to_home_screen4/images/icon192.PNG';
$manifest =
[
"short_name"=> "BetaPage",
"name"=> "BetaPage",
"theme_color"=> "#4A90E2",
"background_color"=> "#F7F8F9",
"display"=> "standalone",
"icons"=>
[
[
"src"=> "images/launcher-icon-1x.png",
"type"=> "image/png",
"sizes"=> "48x48"
],
[
"src"=> "images/launcher-icon-2x.png",
"type"=> "image/png",
"sizes"=> "96x96"
],
[
"src"=> "images/chat1.png",
"type"=> "image/png",
"sizes"=> "144x144"
],
[
"src"=> "images/icon192.png",
"type"=> "image/png",
"sizes"=> "192x192"
]
],
"start_url"=> $starturl
];
header('Content-Type: application/json');
echo json_encode($manifest);
When I reload the webpage then below error occur:
I have to press ctrl+F5 each time to run the code. Why?
I got my solution. MY service-worker.js file was not correct. Now I paste below code in service-worker.js and it wored.
self.addEventListener('fetch', function(event) {});
Related
I am developing one PWA of the ionic capacitor and there is a requirement to load another website in an iframe so from one of the ionic app component I called another site.
iframe.page.html
<ion-header>
<ion-toolbar>
<ion-buttons slot="end" (click)="goBack()">
Close
<ion-icon slot="icon-only" name="close-outline"></ion-icon>
</ion-buttons>
</ion-toolbar>
</ion-header>
<ion-content>
<iframe #iframe height="100%" width="100%" title="test"></iframe>
</ion-content>
iframe.page.ts
export class IframePage implements OnInit, AfterViewInit {
userId = localStorage.getItem('userId');
gameData: any;
gameUrl: any;
docId;
#ViewChild('iframe') iframe: ElementRef;
constructor(private navCtrl: NavController,
private authSrv: AuthService,
private commanSrv: CommannService,
private router:Router) {
firebase.analytics().logEvent('Web_game');
this.iframe.nativeElement.setAttribute('src', 'anotherdomain.com?UID=sadsajdhsakjhdasjhkjsd');
window.addEventListener('message', (event) => {
console.log(event.data);
if (event.data.res === 'win') {
// let routename = commanSrv.getLastRoute();
// navCtrl.navigateForward(routename || 'home_tab');
this.router.navigate(['arcade-outcome', { type: 'arcade_win' }]);
} else if (event.data.res === 'loss'){
this.router.navigate(['arcade-outcome', { type: 'arcade_lose' }]);
} else {
// if (event.data === 'closed') {
let routename = commanSrv.getLastRoute();
navCtrl.navigateBack(routename || 'home_tab');
// }
}
});
}
}
And now
another site is made up of HTML and javascript and here is code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="icon" type="image/png" href="assets/icon/favicon.png" />
<link rel="stylesheet" type="text/css" href="./assets/css/custom.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.4.3/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.4.3/firebase-auth.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.4.3/firebase-firestore.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.4.3/firebase-database.js"></script>
<script src="scripts/firebase.js"></script>
<script type="text/javascript" src="scripts/index.js"></script>
<title>HTML 5 game application</title>
</head>
<body>
<p>Loader screen</p>
<div class="loader"></div>
<script>
$(document).ready(function(){
const serverUrl = 'https://us-central1-domain.cloudfunctions.net/';
var token;
var xhttp = new XMLHttpRequest();
var gamePlayData;
const queryString = window.location.search;
const urlParams = new URLSearchParams(queryString);
const userId = urlParams.get('UID')
const gamePlay = urlParams.get('gameplay')
const mode = urlParams.get('mode')
function getUserDetails(token) {
console.log("getUserDetails start token ", token);
console.log(firebase);
firebase.auth().signInWithCustomToken(token).then((userCredential) => { // execution stop from here.
console.log("getUserDetails end");
var user = userCredential.user;
if (user !== null) {
window.location.replace(`anotherdomain.com/start.html?id=${userId}&gamePlay=${gamePlay}`);
}
})
.catch((error) => {
console.log('error in catch: ', error);
var errorCode = error.code;
var errorMessage = error.message;
// window.history.back();
alert('User is not logged in.')
// parent.postMessage('closed', '*');
});
}
function checkAuth() {
console.log("ajax call start");
$.ajax({
type: "POST",
url: serverUrl + 'checkAuthStatus',
data: { uid: userId },
success: function (response) {
console.log("ajax call end");
//if request if made successfully then the response represent the data
getUserDetails(response.result);
},
error: function (err) {
console.log(err);
}
});
}
checkAuth();
});
</script>
From the line
firebase.auth().signInWithCustomToken(token).then(() => {
Execution cancelled and iframe got closed , window.addEventListener('message', (event) => { got called navigated to ionic application back.
The surprising is, this issue only occurs in iPhone whereas for android it is working fine.
When navigating to another domain site 3rd time then it working and got the success in firebase.auth().signInWithCustomToken(token).then((userCredential) => { .
Please help me.
I have a Javascript file that I'm calling in my Flutter Webview Plugin.
I am trying to return the callback in the console after the onReward method is called. This is the code of my js file:
<html>
<head>
<meta charset='utf-8'>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
<meta http-equiv='X-UA-Compatible' content='IE=edge'>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script type="text/javascript" src="https://s3.amazonaws.com/cdn.theoremreach/v3/theorem_reach.min.js"></script>
</head>
<body>
<iframe src="https://theoremreach.com/respondent_entry/direct?api_key=845783b32b8bef12f1b55a36a8be&user_id=12345"></iframe>
<script type="text/javascript">
var theoremReachConfig = {
apiKey: "",
userId: "12345",
onRewardCenterOpened: onRewardCenterOpened,
onReward: onReward,
onRewardCenterClosed: onRewardCenterClosed
};
var TR = new TheoremReach(theoremReachConfig);
function onRewardCenterOpened(){
console.log("onRewardCenterOpened");
}
function onReward(data){
console.log("onReward: " + data.earnedThisSession);
}
function onRewardCenterClosed(){
console.log("onRewardCenterClosed");
}
if (TR.isSurveyAvailable()) {
TR.showRewardCenter();
}
</script>
</body>
</html>
And this is how I'm calling it in my Dart file:
...
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text("Reward earned"), actions: [
Text("$reward"),
]),
body: WebViewPlus(
javascriptMode: JavascriptMode.unrestricted,
onWebViewCreated: (controller) {
controller.loadAsset(
'assets/tr.html',
);
},
));
}
When I complete a survey I get the following message in my console:
I/chromium( 3560): [INFO:CONSOLE(28)] "onReward: 2", source: http://localhost:56537/assets/tr.html (28)
I want to scan this console message and just add the value of the reward, i.e. 2, in my existing page and display it in the appBar.
Just getting the hang of API calls and fetch and have put together the below code to fetch some info from the Trip Advisor API and log a message to the console using this info.
When I call the fetch request function it logs to the console just fine, but as soon as I wrap it in an event listener callback it no longer executes, why is this?
Appreciate any help!
//This is the fetch function kept in a file names request.js
const findRest = async (reviews, closed) => {
const respond = await fetch(
"https://tripadvisor1.p.rapidapi.com/restaurants/list-by-latlng?limit=30¤cy=EUR&distance=2&lunit=km&lang=en_US&latitude=53.3498&longitude=-6.2603",
{
method: "GET",
headers: {
"x-rapidapi-host": "tripadvisor1.p.rapidapi.com",
"x-rapidapi-key": /* my rapidapi key */
}
}
);
if (respond.status === 200) {
let data = await respond.json();
let newData = await data.data;
let data1 = await newData.filter(
review => parseInt(review.num_reviews) >= reviews
);
let data2 = await data1.filter(close => close.is_closed == closed);
return data2;
} else {
throw new Error("Could not provide results within specified parameters");
}
};
//This is the event listener kept in a file names app.js - both files are active and no problems communicating with each other
document.querySelector(".subButton").addEventListener("click", e => {
e.preventDefault();
console.log("click");
const userReviews = parseInt(document.querySelector(".userRev").value);
const userClose = document.querySelector(".userClose").value;
findRest(userReviews, userClose)
.then(data => {
data.forEach(element => {
console.log(
`${element.name} matches your search criterea and is located at ${element.address}
To make a booking, please call ${element.phone}`
);
});
})
.catch(err => {
console.log(err);
});
});
//HTML below
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width,initial-scale=1" />
<title>What Wine?</title>
<meta name="author" content="Phil My Glass" />
<meta
name="description"
content="An app to help you find the wine you like or something new based on your preferences"
/>
<meta name="keywords" content="wine" />
<link rel="stylesheet" href="style.css" type="text/css" />
</head>
<body>
<header>
<h1>What Restaurant?</h1>
</header>
<main>
<form>
<input class="userRev" /><br />
<input class="userClose" />
<button class="subButton" type="submit">Find!</button>
</form>
</main>
</body>
<script src="req.js" type="text/Javascript"></script>
<script src="app.js" type="text/Javascript"></script>
</html>
Those two lines look like they could break the thread:
const userReviews = parseInt(document.querySelector(".userRev").value);
const userClose = document.querySelector(".userClose").value;
If either one of document.querySelector(".userRev"), document.querySelector(".userClose") is null, that will be uncaught TypeError.
Will know for sure with the HTML.
I'm trying to send a message when the 'q' key is pressed from my index.js file to the script on index.html, but I don't really know why It's not working properly.
Here is my js file
const url = require('url');
const path = require('path');
const {app, BrowserWindow, globalShortcut, ipcMain, webContents} = require('electron');
let mainWindow;
app.on('ready', function(){
// Create new window
mainWindow = new BrowserWindow({
backgroundColor: '#000000',
fullscreen : true,
frame : false,
icon : __dirname + "/res/icon.jpg",
webPreferences: {
nodeIntegration : true
}
});
// Load html in window
mainWindow.loadURL(url.format({
pathname: path.join(__dirname, 'index.html'),
protocol: 'file:',
slashes:true
}))
globalShortcut.register('Esc', () => {
app.quit();
});
globalShortcut.register('q', () => {
leftLight();
});
});
function leftLight() {
mainWindow && mainWindow.webContents.send('key-pressed-q');
console.log("Sending q pressed to html...");
}
And the html
<!DOCTYPE html>
<html lang="en">
<meta name="viewport" content="width=device-width, initial-scale=1">
<head>
<link rel="stylesheet" href="styles.css">
<title>Document</title>
</head>
<body>
<div class = rect_green> <h2 class=blocktext >LEFT FENCER</h2></div>
<div class = rect_red><h2 class=blocktext> RIGHT FENCER</h2> </div>
<div class = crono> <h2 class=crontext>3:00</h2></div>
</body>
<script type="text/javascript">
var ipc = require('electron').ipcRenderer;
ipc.on('key-pressed-q', (e) => {
//var element = document.getElementsByClassName("rect_green");
//element.style["background-color"] = "yellow";
console.log("q pressed in html file");
});
</script>
</html>
The key pressed is detected, but the message is not received by the ipcRenderer. Any mistakes on my code?
It seems like you've got the syntax of .webContents.send( wrong.
You need to provide a channel for your message, E.g. .webContents.send('channel', 'msg'), then you listen for that channel in your page.
A channel can be whatever you want. For example:
Electron js file:
mainWindow.webContents.send('channelNameCanBeAnything', 'key-pressed-q');
Html file:
ipc.on('channelNameCanBeAnything', (msgStr) => {
console.log("q pressed in html file");
console.log(msgStr); // Will output 'key-pressed-q'.
});
See the docs
I was hoping not to asking you for help but here I am
I want to build a simple Chrome extension which marks all paid articles on the home page.
The JS in the medium-extension.js is working through a browser console when is triggered with a button which can be found in the HTML file.
The problem is that I am confused do I need background script, because when I try without one the extension does not work. Now I try without a content script and it still does not work.
I try to do it with one of them because I don't know how to create a connection between background and content scripts.
Here is the code:
manifest.js
{
"name": "Medium cleared",
"version": "1",
"description": "Lets's make Medium great again",
"manifest_version": 2,
"browser_action": {
"default_popup": "index.html"
},
"background": {
"scripts": ["medium-extension.js"],
"persistent": false
}
}
medium-extension.js
function clearMedium() {
Array.from(
document.querySelectorAll('article')
).forEach(el => {
let shouldHide = el.querySelectorAll('span.u-paddingLeft4').length;
if (shouldHide) {
el.style.background = "#FCBFB7";
}
});
Array.from(
document.querySelectorAll('li')
).forEach(el => {
let shouldHide = el.querySelectorAll('span.u-paddingLeft4').length;
if (shouldHide) {
el.style.background = "#FCBFB7";
}
});
Array.from(
document.querySelectorAll('.extremeHero-smallCard.extremeHero-smallCard1.js-trackedPost, .extremeHero-largeCard.js-trackedPost.uiScale.uiScale-ui--small.uiScale-caption--small, .extremeHero-smallCard.extremeHero-smallCard3.js-trackedPost, .extremeHero-smallCard.extremeHero-smallCard2.js-trackedPost, .extremeHero-mediumCard.js-trackedPost')
).forEach(el => {
let shouldHide = el.querySelectorAll('span.u-paddingLeft4').length;
if (shouldHide) {
el.style.background = "#FCBFB7";
}
});
Array.from(
document.querySelectorAll('section.m.n.o.ff.q.d')
).forEach(el => {
let shouldHide = el.querySelectorAll('svg.dl.dm').length;
if (shouldHide) {
el.style.background = "#FCBFB7";
}
});
setTimeout(clearMedium, 5000);
}
<!-- begin snippet: js hide: false console: true babel: false -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="medium-extension.js"></script>
<style>
.button-activate button {
background: #FF82A9;
color: white;
width: 300px;
height:50px;
font-size: 20px;
}
</style>
</head>
<body>
<div class="popup">
<h3>If you are tired of clicking on premium articles and lose one of your precios 3 free slots every month, just click "Clear your Medium" and all premium articles will be colored in red.</h3>
<div class="button-activate">
<button onclick="clearMedium()">Clear your Medium</button>
</div>
</div>
</body>
</html>