Import jQuery with contextBridge - javascript

I'm trying to use contextBridge in Electron, but I keep getting an error when I try to require('jQuery') in preload.js. Here is my preload.js:
const { contextBridge, ipcRenderer } = require('electron')
require('jQuery')
contextBridge.exposeInMainWorld(
'ipcRenderer',
{
send: (channel, arg) => ipcRenderer.send(channel, arg),
on: (event, data) => ipcRenderer.on(event, data)
}
)
As soon as I put require('jQuery'), I get this error:
I want to import APIs like this since it improves security and contextIsolation will be enabled by default in later versions of Electron.

I have no idea if this is secure or not, but I just imported jQuery from index.html:
<head>
<meta charset="UTF-8">
<title>Gemini</title>
<meta http-equiv="Content-Security-Policy" content="script-src 'self'">
<link rel="stylesheet" href="style.css">
<link rel="stylesheet" href="macos.css">
<script type="text/javascript" src="node_modules/jquery/dist/jquery.min.js"></script>
<link rel="stylesheet" href="node_modules/#fortawesome/fontawesome-free/css/all.css">
</head>

Related

How do I link a JavaScript file to HTML in Express?

I’m running a NodeJS server with Express, using Handlebars as the engine.
app.use(express.static(publicDirPath))
(...)
app.engine("hbs",hbs({
extname: "hbs",
defaultView: "main",
layoutsDir: path.join(srcDirPath, "views/layouts"),
partialsDir: path.join(srcDirPath, "views/partials"),
}));
(...)
app.listen(3000, () => {
console.log("Server started at port 3000.");
});
I have a login page:
app.get("/Login", (req, res) => {
res.render("Login", { layout: "Loginlayout" });
});
app.get("/public/js/login.js", (req, res) => {
res.header("Content-Type", "application/javascript")
res.end();
});
– which is using this header:
<head>
<script src="/public/js/login.js" async></script>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
<link rel="stylesheet" href="css/login.css">
<title>Login</title>
</head>
– but I cannot use any of the functions from in login.js.
I also got some "MIME type (“text/html”) mismatch" errors, but I think I fixed them by using
res.header("Content-Type", "application/javascript")
– but I still can’t use any of the functions. I also tried multiple browsers, but nothing worked.
Let app.use(express.static(publicDirPath)) play it's role. Move local js/css file under publicDirPath dir, the express will serve assets' path for you.

Not able to correctly inject files using gulp

My app structure is following:
-gulp
-src
-app
-assets
-css
I want to insert files from "css" folder in index.html which is in "src" folder.
use the below code and set the path accurately.
var inject = require('gulp-inject');
var $ = require('gulp-load-plugins')({ lazy: true });
gulp.task('inject', function () {
var injectStyles = gulp.src(['css/*.css'], { read: false } );
return gulp.src( '/src/index.html')
.pipe($.inject(injectStyles, { relative: true }))
.pipe(gulp.dest('/src'));
});
specially you need to enter styles comment tag in your html file as below:
<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>
<!-- inject:css -->
<!-- endinject -->
</head>

Socket.io variable not defined in Phonegap mobile application

I'm trying to develop a mobile application using Phonegap with RequireJs, Backbone, jQuery and I'm running into a problem each time I try to include the requirejs script tag:
<script data-main="js/app" src="node_modules/requirejs/require.js</script>
After I include this, I get the following error:
ReferenceError: io is not defined.
I'm not using socket.io but I think that Phonegap is using it in order to refresh the page in the browser.
This is my index.html file:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="format-detection" content="telephone=no" />
<meta name="msapplication-tap-highlight" content="no" />
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width" />
<!-- This is a wide open CSP declaration. To lock this down for production, see below. -->
<meta http-equiv="Content-Security-Policy" content="default-src * 'unsafe-inline'; style-src 'self' 'unsafe-inline'; media-src *" />
<title>Hello World</title>
</head>
<body>
something nice
<!-- Content -->
<script type="text/javascript" src="cordova.js"></script>
<script data-main="js/app" src="node_modules/requirejs/require.js"></script>
</body>
</html>
This is my js/app.js file:
requirejs.config({
baseUrl: 'js',
shim: {
'socket.io': {
exports: 'io'
},
'underscore': {
exports: '_'
},
'backbone': {
deps: [
'underscore',
'jquery'
],
exports: 'Backbone'
}
},
paths: {
jquery: 'jquery.min',
underscore: 'lodash.min',
backbone: 'backbone',
socketio: '../socket.io/socket.io'
// package: 'node_modules'
}
// map: {
//
// '*': {
// 'jquery': 'private/jquery'
// },
//
// 'private/jquery': {
// 'jquery': 'jquery'
// }
// }
});
I'm using Phonegap version 6.3.4.
Could you please tell me, what should i do in order to get rid of the error?
Thank you!
I've managed to solve it by reading these articles:
Has Phonegap integrate socket.io in version 3.5.0-0.20.10?
https://github.com/phonegap/phonegap-app-developer/issues/339
Mismatched anonymous define() module
Here's my fix:
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript">
// Fixes "Uncaught ReferenceError: io is not defined".
// We need to load RequireJs after socket.io has been loaded.
function injectRequireJs() {
var h = document.getElementsByTagName('body')[0];
var s = document.createElement('script');
s.type = 'text/javascript';
s.src = 'node_modules/requirejs/require.js';
s.setAttribute('data-main', 'js/bootstrap');
h.appendChild(s);
}
setTimeout(function(){
injectRequireJs();
}, 1);
</script>

App takes too long to load in production

I have pushed my angular 2 app on heroku but it takes too long to load.
is there a way to bundle everything up because right now i have this in my index.html
<html>
<head>
<base href="/">
<title>Angular 2 Arc</title>
<link rel="icon" type="image/x-icon" href="favicon.ico">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<ng2-app>Loading...</ng2-app>
<!-- Load Angular 2 Core libraries -->
<script src="es6-shim/es6-shim.min.js"></script>
<script src="systemjs/dist/system-polyfills.js"></script>
<script src="angular2/bundles/angular2-polyfills.js"></script>
<script src="systemjs/dist/system.src.js"></script>
<script src="rxjs/bundles/Rx.js"></script>
<script src="angular2/bundles/angular2.dev.js"></script>
<script src="angular2/bundles/router.dev.js"></script>
<script src="angular2/bundles/http.js"></script>
<!-- Load Bootstrap and Jquery -->
<script src="lib/jquery/jquery.min.js" charset="utf-8"></script>
<script src="lib/bootstrap/js/bootstrap.min.js" charset="utf-8"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/github-fork-ribbon-css/0.2.0/gh-fork-ribbon.min.css" />
<link rel="stylesheet" href="/lib/bootstrap/css/bootstrap.min.css" media="screen" title="no title" charset="utf-8">
<link rel="stylesheet" href="assets/css/app.css">
<!-- Configure SystemJS -->
<script>
System.config({
defaultJSExtensions: true,
packages: {
boot: {
format: 'register',
defaultExtension: 'js'
}
}
});
System.import('js/boot')
.then(null, console.error.bind(console));
</script>
</body>
</html>
My setup is express server and system JS.
server.js
var express = require('express');
var bodyParser = require('body-parser')
var fs = require("fs");
// initialize express
var app = express();
// declare build and node_module paths
app.use(express.static("./build"));
app.use(express.static("./node_modules/"));
// parse request body
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
var body;
// route to send json data from angular 2
app.post('/export', function(req, res){
body = req.body;
res.json("Got the data!");
fs.writeFile('parameters.json', JSON.stringify({body}, null, 4), function (err) {
if (err) return console.log(err);
console.log('Data json file created!');
});
});
// start server
app.listen(process.env.PORT || "3001", function(){
console.log("Express server running on localhost:3001");
});
If its the free heroku tier its probably because its sleeping when you request it?
You can minify and concatenate your js files to decrease load times.
Here is a guide on how to do that with gulp tasks:
https://caveofcode.com/2016/03/gulp-tasks-for-minification-and-concatenation-of-dependencies-in-angularjs/

EXCEPTION: TypeError: undefined is not an object (evaluating 'pipe.constructor') in Ionic 2?

My Ionic 2 application working fine on chrome browser, it gives expected output. But when it run on simulator or browser gives below error.
Here is the code I'm using:
<label class="time">{{appointment.DateSent | date:"HH"}}:{{ appointment.DateSent| date:"mm"}}</label>
<label class="month">{{appointment.DateSent| date:"MMM"}}</label>
<label class="day">{{appointment.DateSent| date:"dd"}}</label>
<label class="year">{{appointment.DateSent| date:"yyyy"}}</label>
Class implementation:
import {Page, NavController, NavParams} from 'ionic/ionic';
import { Component, Pipe, PipeTransform, Inject, OnInit} from 'angular2/core';
import 'rxjs/add/operator/map';
import { Http, Headers, URLSearchParams } from 'angular2/http';
import {SERVER_URL, appName, alertAppName} from '../services/config';
import {AppointmentsDetailPage} from '../appointments-detail/appointments-detail';
import {MessagesService} from '../services/messages-service';
var today = new Date();
#Page({
templateUrl: 'build/pages/appointments/appointments.html',
providers: [MessagesService]
})
export class AppointmentsPage implements PipeTransform {
constructor(http: Http, nav: NavController, messagesService:MessagesService, navParams:NavParams) {
this.http = http;
this.messagesService = messagesService;
this.nav = nav;
this.selectedItem = navParams.get('item');
}
ngOnInit() {
this.messagesService.getAppointmentList()
.subscribe(data => {
var appointments = new Array();
for(var i in data){
var key = data[i];
appointments.push({
MessageID: key.MessageID,
CategoryID: key.CategoryID,
DateSent: new Date(key.DateSent),
Title: key.Title,
MessageContent: key.MessageContent,
Sender: key.Sender,
Recipient: key.Recipient,
DateReceived: key.DateReceived,
DateRead: key.DateRead,
Note_Direction: key.Note_Direction,
Viewed: key.Viewed,
AppointmentDateTime: key.AppointmentDateTime,
MessageAttachments: key.MessageAttachments
});
}
this.appointments = appointments;
All the date pipe were working alright in Chrome browser with no error, but it gives below exception on simulator or device (took from Safari simulator debugging)
Edited:
Index.html
<!DOCTYPE html>
<html dir="ltr" lang="en">
<head>
<title>Ionic</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">
<!--<meta http-equiv="Content-Security-Policy" content="img-src 'self' data:; default-src 'self' http://XX.XX.XX.XX:8084/mypp/">-->
<!--<meta http-equiv="Content-Security-Policy" content="default-src *; script-src 'self' 'unsafe-inline' 'unsafe-eval' *; style-src 'self' 'unsafe-inline' *">-->
<meta name="format-detection" content="telephone=no">
<meta name="msapplication-tap-highlight" content="no">
<link rel="stylesheet" href="build/css/font-awesome.min.css">
<link ios-href="build/css/app.ios.css" rel="stylesheet">
<link md-href="build/css/app.md.css" rel="stylesheet">
</head>
<body>
<ion-app></ion-app>
<script src="node_modules/es6-shim/es6-shim.min.js"></script>
<script src="node_modules/systemjs/dist/system-polyfills.js"></script>
<script src="lib/ngCordova/dist/ng-cordova.js"></script>
<script src="cordova.js"></script>
<script src="build/js/app.bundle.js"></script>
</body>
</html>
You should load polyfills (Chrome can run Angular without them):
<script src="node_modules/es6-shim/es6-shim.min.js"></script>
<script src="node_modules/systemjs/dist/system-polyfills.js"></script>
Sasxa's answer helped me to solve this issue. Although I tried to specify path it doesn't seems to find its resource. Following resources helped me to get the answer. As Sasxa pointed out, Safari needs Intl polyfill.
https://www.npmjs.com/package/intl
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl#Browser_Compatibility
I tried to install it using NPM and Bower it didn't work, finally I settle with using CDN location as it worked for me.
<script src="https://cdn.polyfill.io/v2/polyfill.min.js?features=Intl.~locale.en"></script>

Categories

Resources