gmaps + requirejs + async + laravel 5 : Cannot load gmaps using async - google-maps

RequireJS + Laravel 5 + Gmaps + async = not working
Can somebody help me with loading google maps using async plugin ?
I also tried goog plugin but it was unsuccessful too.
It throws following error:
I can load map only synchronically but it is unsafe.
here is my code :
welcome.blade.php
<head>
<title>Roads API Demo</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
<link rel="stylesheet" type="text/css" href="{{ URL::asset('assets/css/style.css') }}">
<script data-main="{{ URL::asset('assets/js/config') }}" type="application/javascript" src="{{ URL::asset('assets/js/lib/require.js') }}"></script>
</head>
assets/js/gmapsApi.js
define(['async!http://maps.google.com/maps/api/js?sensor=false'], function() {
console.log("HIIIIIIIIIIIIII");
// When I delete async and put only
// http://maps.google.com/maps/api/js?sensor=false
// Then works fine .
});
assets/js/config.js
requirejs.config({
baseUrl: "assets/js/lib", //require.js path=assets/js/lib/require.js
paths: {
main: "../main",
gmapsApi : "../gmapsApi"
},
waitSeconds: 0
});
requirejs(["gmapsApi"]);
IMPORTANT NOTE : require.js path=assets/js/lib/require.js
All scripts are loaded good, I checked Sources and Network tab in chrome.
in module assets/js/gmapsApi.js
Not working: async!http://maps.google.com/maps/api/js?sensor=false
Working fine : http://maps.google.com/maps/api/js?sensor=false

It looks like HTTPS protocol is needed on my local server (vhost) because google maps is provide apis only for servers that are treated as a secure origin over HTTP (HTTPS protocol).
Hire is link : https://sites.google.com/a/chromium.org/dev/Home/chromium-security/deprecating-powerful-features-on-insecure-origins
So in my gmapsApi.js I also provide url to google maps over https protocol (which is required, because I already set my local server on https protocol)
assets/js/gmapsApi.js
define(['async!https://maps.googleapis.com/maps/api/js?v=3&libraries=places'], function() {
console.log("HIIIIIIIIIIIIII");
});
This solved problem for me. And gmaps api are loaded asynchronously (using async plugin).

Related

ASP.NET Core 6 Web app with index.html using <base href> would not load script files

I have an ASP.NET Core 6 app and I host my Angular app with it, among other things (from Program.cs):
...
app.Use(async (context, next) =>
{
RewriteXFrameOptionsHeader(context);
await next();
if (context.Response.StatusCode == 404 && !Path.HasExtension(context.Request.Path.Value))
{
context.Request.Path = "/";
await next();
}
});
app.UseDefaultFiles(new DefaultFilesOptions {DefaultFileNames = new List<string> {"index.html"}});
app.UseStaticFiles();
...
It it doesn't work, because scripts are not loaded. The Angular index.html uses base href and relative paths to js sources, like so:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<base href="/ngxapp">
...
<script src="runtime.7cef1b4acdcbe752.js" type="module"></script><script src="polyfills.e4b5afbd657fbe4a.js" type="module"></script><script src="main.c8a9bcf210ef6760.js" type="module"></script>
</body>
</html>
Even though script src's contain relative paths, the browser tries to load script from the root. Here's what dev tools Network tab shows:
Request URL: https://localhost:7101/runtime.7cef1b4acdcbe752.js
MDN docs for base href state:
The HTML element specifies the base URL to use for all relative URLs in a document.
Why then scripts are being loaded from root?

Forwarded URL renders the webpage in half the height as normal for a Flutter Web app hosted in Firebase

I have a firebase hosted Flutter Web application which is a game. Since the URL for the Firebase hosted site (https://jw-daily.web.app) is difficult to remember for users, I bought a domain name (joinedwords.com) and redirected the URL to the firebase hosted site.
Problem is that when I type the domain URL i.e. joinedwords.com, the website renders in only half the height like below:
However, if I type the original URL (https://jw-daily.web.app) in the browser, the webpage renders in full like below:
All that I have done is with my domain provider, I have set a forward with masking of joinedwords.com => https://jw-daily.web.app/
I looked up all the other solutions around why a webpage is rendering in half. However most of them are asking to make changes to the code and I don't want to do that since the original URL is working fine. Incidentally this issue is happening only on mobile browsers and not happening on desktop. In desktop, the website renders correctly regardless of which URL is typed.
Please suggest if you are aware of how we can solve this problem. Here is my index.html file.
<!DOCTYPE html>
<html prefix="og: http://ogp.me/ns#">
<head>
<!--
If you are serving your web app in a path other than the root, change the
href value below to reflect the base path you are serving from.
The path provided below has to start and end with a slash "/" in order for
it to work correctly.
For more details:
* https://developer.mozilla.org/en-US/docs/Web/HTML/Element/base
-->
<base href="/">
<meta charset="UTF-8">
<meta content="IE=Edge" http-equiv="X-UA-Compatible">
<meta name="description" content="A Daily Word Game">
<meta image="" />
<meta property="og:image:url" content="https://s3.us-east-2.amazonaws.com/joint.words/joined-xxx.png"
property="og:image:secure_url" content="https://s3.us-east-2.amazonaws.com/joint.words/joined-xxx.png"
property ="og:image:alt" content="Joined Words Logo"
property="og:image:type" content="image/png"
/>
<!--
property="og:image:width" content="100"
property="og:image:height" content="100"
-->
<!-- iOS meta tags & icons -->
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<meta name="apple-mobile-web-app-title" content="Joined Words">
<link rel="apple-touch-icon" href="https://s3.us-east-2.amazonaws.com/joint.words/joined-256.png">
<!-- Favicon -->
<link rel="shortcut icon" href="favicon.png" type="image/x-icon">
<link rel="icon" href="favicon.png" type="image/x-icon">
<title>Joined Words</title>
<link rel="manifest" href="manifest.json">
<meta name="google-site-verification" content="XXXXXXXXX-XXXXXX" />
/>
<!-- Global site tag (gtag.js) - Google Ads: xxxxxxxxx -->
<script async src="https://www.googletagmanager.com/gtag/js?id=AW-xxxxxxxxxxx"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'AW-xxxxxxxxxxx');
</script>
<!-- Event snippet for Website traffic conversion page -->
<script>
gtag('event', 'conversion', {'send_to': 'xxxxxxxxxxxxxxxxxxx'});
</script>
</head>
<body>
<!-- This script installs service_worker.js to provide PWA functionality to
application. For more information, see:
https://developers.google.com/web/fundamentals/primers/service-workers -->
<script>
var serviceWorkerVersion = null;
var scriptLoaded = false;
function loadMainDartJs() {
if (scriptLoaded) {
return;
}
scriptLoaded = true;
var scriptTag = document.createElement('script');
scriptTag.src = 'main.dart.js?version=1';
scriptTag.type = 'application/javascript';
document.body.append(scriptTag);
}
if ('serviceWorker' in navigator) {
// Service workers are supported. Use them.
window.addEventListener('load', function () {
// Wait for registration to finish before dropping the <script> tag.
// Otherwise, the browser will load the script multiple times,
// potentially different versions.
var serviceWorkerUrl = 'flutter_service_worker.js?v=' + serviceWorkerVersion;
navigator.serviceWorker.register(serviceWorkerUrl)
.then((reg) => {
function waitForActivation(serviceWorker) {
serviceWorker.addEventListener('statechange', () => {
if (serviceWorker.state == 'activated') {
console.log('Installed new service worker.');
loadMainDartJs();
}
});
}
if (!reg.active && (reg.installing || reg.waiting)) {
// No active web worker and we have installed or are installing
// one for the first time. Simply wait for it to activate.
waitForActivation(reg.installing ?? reg.waiting);
} else if (!reg.active.scriptURL.endsWith(serviceWorkerVersion)) {
// When the app updates the serviceWorkerVersion changes, so we
// need to ask the service worker to update.
console.log('New service worker available.');
reg.update();
waitForActivation(reg.installing);
} else {
// Existing service worker is still good.
console.log('Loading app from service worker.');
loadMainDartJs();
}
});
// If service worker doesn't succeed in a reasonable amount of time,
// fallback to plaint <script> tag.
setTimeout(() => {
if (!scriptLoaded) {
console.warn(
'Failed to load app from service worker. Falling back to plain <script> tag.',
);
loadMainDartJs();
}
}, 4000);
});
} else {
// Service workers not supported. Just drop the <script> tag.
loadMainDartJs();
}
</script>
<!-- Initialize Firebase -->
<script src="/__/firebase/9.0.2/firebase-app.js"></script>
<script src="/__/firebase/9.0.2/firebase-analytics.js"></script>
<script src="/__/firebase/init.js"></script>
<!-- Initialize app -->
<script src="main.dart.js?version=15 " type="application/javascript"></script>
</body>
</html>
Found an answer to the issue I was facing. Here is the link to the same:
Bootstrap Responsive Design Fails with Web Forwarding
This is because you are using a framed redirect which essentially loads up the target website in an iFrame. Doing so loses any responsive capabilities. What you are best doing is changing your web forwarding method to actually forward to the new URL using a non-framed redirect. This will then properly load up the target URL in the users browser and all the responsive capabilities that go with it.

Next.js PWA (Service Worker + Manifest.json)

I am using Next.js to develop a Server Side Rendering website and I want to make it a Progressive Web App but the problem I couldn't find the way to make it happen correctly.
When I build the application it serves correctly the service worker but there is no manifest.json and in some projects examples it serves the manifest.json but I tried it in Lighthouse audit and it says
Service worker does not successfully serve the manifest's start_url
One of the examples I used
Create Next App With Service Worker Precache
I think that the problem is that the start_url is . or / and not a valid file because in Next.js there is no index.html to serve from the start.
In summary
I am looking for an example using Next.js to build it to a dist folder and when I serve it it has a valid Service Worker and a valid Web Manifest.
A. Some file are expected to be found at "/"
You have this error because browsers expect some files to be served from the root of the server, including:
/manifest.json
/sitemap.xml
/favicon.ico
/robots.txt
/browserconfig.xml
/site.webmanifest
While the majority of these paths can be set with meta tags, older browsers just ignore them and error if these exact file names are not served.
B. Configure alternative paths and use NextJS static file
At the time of writing, there is ongoing work for supporting offline in NextJS. But it's not ready yet.
If you don't need to support older browsers and you don't want advanced SEO, you can use NextJS's Head component (see documentation) to define the manifest.json path like you would for any NextJS static file:
import Head from "next/head"
export default () => (
<Head>
<link rel="manifest" href="/static/manifest.json" />
<link rel="manifest" href="/static/site.webmanifest" />
<link rel="shortcut icon" href="/static/favicon.ico"
</Head>
)
Please note that robots.txt cannot be serve from a subdirectory (source), so this solution is not a good fit if you need to define this file.
C. Serve these files like expected
The proper solution would be to serve these files from your express server like so
const { createServer } = require('http')
const { parse } = require('url')
const next = require('next')
const { join } = require('path')
const port = parseInt(process.env.PORT, 10) || 3000
const dev = process.env.NODE_ENV !== 'production'
const app = next({ dev })
const handle = app.getRequestHandler()
app.prepare()
.then(() => {
createServer((req, res) => {
const parsedUrl = parse(req.url, true)
const rootStaticFiles = [
'/manifest.json',
'/sitemap.xml',
'/favicon.ico',
'/robots.txt',
'/browserconfig.xml',
'/site.webmanifest',
]
if (rootStaticFiles.indexOf(parsedUrl.pathname) > -1) {
const path = join(__dirname, 'static', parsedUrl.pathname)
app.serveStatic(req, res, path)
} else {
handle(req, res, parsedUrl)
}
})
.listen(port, (err) => {
if (err) throw err
console.log(`> Ready on http://localhost:${port}`)
})
})
Note: This code directly comes from the NextJS examples repository
here are the steps to make your next.js progressive. check the example
npm i next-pwa
next.config.json
const withPWA = require("next-pwa");
module.exports = withPWA({
pwa: {
dest: "public",
},
...
});
add manifest.json and icons to public folder from the example. However, icons directory is missing "maskable_icon.png". So create a maskable icon from here then add this to "manifest.json".
{
"src": "path/to/maskable_icon.png",
"sizes": "196x196",
"type": "image/png",
"purpose": "any maskable"
}
add those tags to import Head from "next/head". Head is used for better SEO setting. check the documentation*
<meta charSet="utf-8" />
<meta httpEquiv="X-UA-Compatible" content="IE=edge" />
<meta
name="viewport"
content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no"
/>
<meta name="description" content="Description" />
<meta name="keywords" content="Keywords" />
<title>Next.js PWA Example</title>
<link rel="manifest" href="/manifest.json" />
<link
href="/icons/favicon-16x16.png"
rel="icon"
type="image/png"
sizes="16x16"
/>
<link
href="/icons/favicon-32x32.png"
rel="icon"
type="image/png"
sizes="32x32"
/>
<link rel="apple-touch-icon" href="/apple-icon.png"></link>
<meta name="theme-color" content="#317EFB" />
</Head>
lastly check if it is working. add Lighhouse extension to chrome dev tools from chrome app store and run start the performance.

AdMob banner not displayed in Phonegap

i want to create an android app using phonegap , with a simple basic HTML page as showed in this tutorial.
http://pointdeveloper.com/how-to-add-banner-ads-to-phonegap...
https://phonegap.com/blog/2016/08/09/appfeel-guest-post/
After adding the following line to "config.xml"
<gap:plugin name="phonegap-admob" source="npm"/>
here is my "index.html" file
<!DOCTYPE html>
<html>
<head>
<title>Title Of The App</title>
<meta name="viewport" content="user-scalable=no, initial-scale=1,
maximum-scale=1, minimum-scale=1, width=device-width, min-height=device-
height" />
<link rel="stylesheet" type="text/css" href="css/index.css">
</head>
<body onload="domLoaded()">
<header>pointDeveloper.com</header>
<div class="wrapper">Please Subscribe To My Channel and like the video
</div>
<footer class="footer">This is spartaaaa</footer>
<script src="cordova.js"></script>
<script type="text/javascript" src="js/index.js" ></script>
<script type="text/javascript" >
function adSetter(){
alert(navigator.userAgent);
var admobid = {};
// select the right Ad Id according to platform
if( /(android)/i.test(navigator.userAgent) ) {
admobid = { // for Android
banner: 'ca-app-pub-6136762217480399/8690615372',
interstitial: 'ca-app-pub-6136762217480399/5002296586'
};
} else if(/(ipod|iphone|ipad)/i.test(navigator.userAgent)) {
admobid = { // for iOS
banner: 'ca-app-pub-6869992474017983/4806197152',
interstitial: 'ca-app-pub-6869992474017983/7563979554'
};
} else {
admobid = { // for Windows Phone
banner: 'ca-app-pub-6869992474017983/8878394753',
interstitial: 'ca-app-pub-6869992474017983/1355127956'
};
}
if(AdMob) AdMob.createBanner( {
isTesting:true, //Remove this Before publishing your app
adId:admobid.banner,
position:AdMob.AD_POSITION.BOTTOM_CENTER,
autoShow:true} );
}
function onDeviceReady(){
alert("device ready");
adSetter();
}
function domLoaded(){
document.addEventListener("deviceready", onDeviceReady, false);
}
</script>
</body>
</html>
After lot of testing on my android phone, even exporting the apk in the phonegap build,
the apps is displpayed , but the bottom banner is nowhere
did i miss something ?
thanks in advance
edit: Here are the errors shown in Chrome JavaScript Debugger Tools
Uncaught ReferenceError: domLoaded is not defined
at onload ((index):10)
:3000/cordova_plugins.js Failed to load resource: the server responded with a status of 500 (Internal Server Error)
(index):27 Uncaught ReferenceError: admob is not defined
at initAds ((index):27)
at Channel.onDeviceReady ((index):97)
at Channel.fire (cordova.js:777)
at cordova.js:231
:3000/favicon.ico Failed to load resource: the server responded with a status of 404 (Not Found)
Its likely that you need to configure the cordova-plugin-whitelist to allow Admob to access the network.
edit:
Add the plugin to your config.xml:
<plugin name="cordova-plugin-whitelist" />
Start with fully open access (in your config.xml) and see if your request is successful:
<access origin="*" />
If that works then you should determine which exact domains you need access to and restrict to that. If your requests still don't work then the problem may be somewhere else. Connect a JavaScript debugger (safari or Chrome) and see what errors are being thrown.

google sign in not returning error also not signing in

I am trying to make google sign in work on my intranet site which currently uses integrated windows authentication - I want to get away from that because I need to support ChromeBooks and pretty much everything here is going google......
This is what IS working:
I get a sign in button. I can see in the console log that it is using my google developer client id:
XHR finished loading: GET "https://accounts.google.com/o/oauth2/iframerpc?action=checkOrigin&origin=ht…d=777682448638-5tpyaddayaddyadddarvnbr3p6.apps.googleusercontent.com".
If I click the button on a machine where I am not logged into google I will geta prompt to log into google.
If I click the button on a machine where I am logged into google but have not visited this site before then I will get the authorization request for my email and profile to be shared with my web application.
If I have done the above, and click the button then there is a flash of a pop-up window that goes away immediately.
What is NOT working:
My website never gets any onSuccess back....... so the button ALWAYS says "Sign in with Google" I don't get to the next step of "Signed in as molly ......"
Here is a shortended version of my code - please note that right now my website uses the integrated windows authentication - that is what I am trying to port away from so we can use ChromeBooks and other computers that are not using our windows login.
this is from my _Layout.cshtml page
#{
var username = WebSecurity.CurrentUserName;
}
<!DOCTYPE html>
<html lang="en">
<head>
<title>Rutland City Public Schools - ACADEMIC SITE</title>
<link href="~/Styles/Styles.css" rel="stylesheet" type="text/css"/>
<link href="~/Styles/PrintStyles.css" rel="stylesheet" type="text/css" media="print"/>
<meta http-Equiv="Cache-Control" Content="no-cache">
<meta http-Equiv="Pragma" Content="no-cache">
<meta http-Equiv="Expires" Content="0">
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
#RenderSection("script", required: false)
<meta name="google-signin-scope" content="profile email">
<meta name="google-signin-client_id" content="777682448638-5tpyaddayaddayaddavnbr3p6.apps.googleusercontent.com">
</head>
<body>
<div id="topRight">
Hello: #username <br> <br>
<div id="my-signin2" align="center" ></div>
<script>
function onSuccess(googleUser) {
console.log('Logged in as: ' + googleUser.getBasicProfile().getName());
}
function onFailure(error) {
console.log(error);
}
function renderButton() {
gapi.signin2.render('my-signin2', {
'scope': 'https://www.googleapis.com/auth/plus.login',
'width': 150,
'height': 30,
'longtitle': true,
'theme': 'light',
'onsuccess': onSuccess,
'onfailure': 'oops!'
});
}
</script>
<script src="https://apis.google.com/js/platform.js?onload=renderButton" async defer></script>
ignore google button!
</div>
<div id="mainContent">
#RenderBody()
</div>
</body>
</html>
If I open up "Inspect Element" when I am in chrome I can see that under the network tab it clearly goes off and does some gets to google. In the console tab I only see the XHR finished loading: GET "https://accounts.google................." message.
What is going on here? Why am I not getting the onSuccess?
Thank you!!!!
Added more notes:
I added a link:
Sign in
that calls this function:
function signIn() {
var auth2 = gapi.auth2.getAuthInstance();
console.log(auth2);
From the console results I can see my website, and my client id, but again I see nothing about my actual user.
jF {zd: Object, po: "single_host_origin", zt: true, ha: true, G: undefined…}
B: bY
B: "777682448638-5tp3rss17g1qarc3em0opcr4rvnbr3p6.apps.googleusercontent.com"
Db: "http://rcps"
Ei: undefined
El: undefined
G: "google"
Ka: false
Ld: Object
openid.realm: undefined
redirect_uri: "http://rcps/academic/academic"
response_type: "token id_token"
scope: "openid profile email"
With the Google Sign-In (gapi.auth2) JavaScript client libraries, you should probably be using listeners to check the state of the client. I'm not sure exactly how you're rendering the button but you might want to take a good look at the Google Sign-in quickstart.
Although I have found using listeners to have advantages over using the success callback, the following code works for me (I see onWin upon sign-in with the z variable containing the authorization response):
function onFail(z){ alert('Fail' + JSON.stringify(z)); }
function onWin(z){ alert('Win' + JSON.stringify(z)); }
gapi.load('auth2', function() {
gapi.signin2.render('signin-button', {
scope: 'https://www.googleapis.com/auth/plus.login',
onsuccess: onWin,
onfail: onFail,
fetch_basic_profile: false });
gapi.auth2.init({fetch_basic_profile: false,
scope:'https://www.googleapis.com/auth/plus.login'}).then(
function (){
console.log('init');
auth2 = gapi.auth2.getAuthInstance();
auth2.isSignedIn.listen(updateSignIn);
auth2.then(updateSignIn());
});
});
Do things when sign-in changes (e.g. show/hide authorized UI):
var updateSignIn = function() {
console.log('update sign in state' + auth2.isSignedIn.get());
}
At any point when auth2.isSignedIn.get() returns true, you can use auth2.currentUser.get() to retrieve the profile data for the currently signed in user.
I had similar problems when testing on localhost. When I pushed my code onto my production server the simple example provided by Google worked perfectly as advertised. The button's values changes or stays accordingly even after a page refresh.
Perhaps your browser is configured to block third party cookies. If so, disable that feature. You may also want to have a note on your login page mentioning that third party cookies are required so that your users will know to do the same.