Vue - watch url without VueRouter - url

Is it possible to react on URL changes in a Vue component, without including VueRouter?
In case VueRouter is present, we can watch $route, however, my application does not rely on VueRouter.
export default {
watch: { '$route': route => console.log(window.location.href) }
}

Before I used vue router, I did something like this...
data: function() {
return {
route: window.location.hash,
page: 'home'
}
},
watch: {
route: function(){
this.page = window.location.hash.split("#/")[1];
}
}

Related

My Vue PWA app shows white blank page on iOS

I am currently working one a Vuejs PWA app (using Vue CLI 3). My app works fine on Android, Windows, and macOS, but it only shows a white blank page on ios. More specifically, when I use an iPhone and access my app with Safari or Chrome, it all shows a white page. When I add my app to the home screen of the iPhone, when I open it up, it still shows a white page.
this is link to my app.
White blank screen
I have tried many workarounds here but it not work.
here are some parts of my code:
vue.config.js
module.exports = {
transpileDependencies: ['vuetify'],
pwa: {
workboxPluginMode: 'InjectManifest',
workboxOptions: {
swSrc: 'src/config/firebase-messaging-sw.js',
exclude: [/\.map$/, /_redirects/],
},
manifestOptions: {
start_url: 'index.html',
},
name: 'AppName',
appleMobileWebAppCapable: 'yes',
},
};
router
const router = new VueRouter({
mode: "history",
base: process.env.BASE_URL,
routes: [
{
path: "/",
name: "RenterMainView",
component: RenterView,
children: [
{
path: "index.html",
name: "Home",
component: Home,
meta: { guest: true },
alias: ""
},
{
path: "detail/:typeId",
name: "HostelDetail",
component: HostelDetail,
meta: { guest: true }
}
]
}
]
});
router.beforeEach((to, from, next) => {
if (to.matched.some((record) => record.meta.requiresAuth)) {
if (window.$cookies.get('jwt') === null) {
// not logged in
next({
name: 'Login',
params: { nextUrl: to.path, preUrl: from.path },
});
} else {
// logged in
const role = window.$cookies.get('role');
if (to.matched.some((record) => record.meta.is_vendor)) {
if (role === 'vendors') {
next();
} else {
next(from.path);
}
} else if (to.matched.some((record) => record.meta.is_admin)) {
if (role === 'admins') {
next();
} else {
next(from.path);
}
} else if (to.matched.some((record) => record.meta.is_renter)) {
if (role === 'renters') {
next();
} else {
next(from.path);
}
} else {
next();
}
}
} else if (to.matched.some((record) => record.meta.guest)) {
// not require authen
next();
} else {
// not require authen
next();
}
});
Try changing the start_url
I found that on
Chrome Windows
Chrome MacOS
Android
I was OK to use quite a wide variety of start_url values, such as the "index.html" that you have, or "/index.html", etc.
However on iOS, I had to use
start_url: "."
The other values were fine on the other platforms, but gave a blank white screen on iOS.
Try creating a blank PWA with the Vue CLI
Does that work correctly on iOS?
Then step by step change it to contain your app.
Find out where it breaks.
That's how I found the start_url issue.
I hope that this could help someone. In this project, I make an PWA app using Vue, and I use Firebase Cloud Messagging to send notification from server to client. Unfortunaly, due to some restrictions on iOS, FCM doesn't work on it, that is why the application show a white page on iOS. So, the solution is to disable FCM on iOS
if (firebase.messaging.isSupported()) { // your code go here }
using above code to disable FCM on firebase service worker file

Can't open a deeplink in foreground with React Native for iOS

We are using firebase deeplinks in a react native application built for both iOS and Android.
Example deeplink: https://monedacacao.page.link/RifKomEk3bhNM9CW9?d=1
Expected behavior:
User scans a QR Code that contains a deeplink in QRScannerScreen
onSuccess (e) is triggered and the link is opened using Linking.openUr()
In ReduxNavigation Firebase.links().onLink() is triggered and redirects the user to SendDestinataryScreen
Actual behavior
In Android this works as intended, but on iOS Linking.openURL(e.data) opens a browser with the Firebase fallback link instead of triggering the Firebase.links.onLin() action.
If the link is clicked from outside the application it behaves as intended. So this problem only occurs when opening the link from inside the application.
QRScannerScreen.js
...
onSuccess (e) {
Linking
.openURL(e.data)
.catch(err => console.error('An error occured', err))
}
...
ReduxNavigation.js
import React from 'react'
import { BackHandler, Platform } from 'react-native'
import { addNavigationHelpers, NavigationActions } from 'react-navigation'
import { createReduxBoundAddListener } from 'react-navigation-redux-helpers'
import { connect } from 'react-redux'
import firebase from 'react-native-firebase'
import AppNavigation from './AppNavigation'
class ReduxNavigation extends React.Component {
constructor (props) {
super(props)
// handle deeplinking
firebase.links().onLink((url) => {
console.log('URL', url)
if (this.props.token) {
this.props.dispatch(NavigationActions.push({
routeName: 'SendDestinataryScreen',
params: { link: url }
}))
} else {
this.props.dispatch(NavigationActions.push({
routeName: 'LoginScreen'
}))
}
})
}
componentDidMount () {
if (Platform.OS === 'ios') return
BackHandler.addEventListener('hardwareBackPress', () => {
const { dispatch, nav } = this.props
// change to whatever is your first screen, otherwise unpredictable results may occur
if (nav.routes.length === 1 && (nav.routes[0].routeName === 'LaunchScreen')) {
return false
}
// if (shouldCloseApp(nav)) return false
dispatch({ type: 'Navigation/BACK' })
return true
})
}
componentWillUnmount () {
if (Platform.OS === 'ios') return
BackHandler.removeEventListener('hardwareBackPress')
}
render () {
return <AppNavigation navigation={addNavigationHelpers({ dispatch: this.props.dispatch, state: this.props.nav, addListener: createReduxBoundAddListener('root') })} />
}
}
const mapStateToProps = state => ({ nav: state.nav, token: state.authentication.token })
export default connect(mapStateToProps)(ReduxNavigation)

Angular rails templates not working in production

I use aws ec2 with elastic beanstalk(eb) to deploy application then I try to access application I got empty page and no error on console. I put my template under
app/assets/templates/simple_template.html.erb
Then I tried to check with server in rails log (production.log) nginx log (access.log , error.log) is no any error in these logs
I search on Google then I found some people talk about
gem sprockets
then I put gem 'sprockets', '~> 3.0' to gem file is still not working
More Detail
Empty page
Inspect HTML
jdgray I tried many debug I just found and post it in here https://github.com/pitr/angular-rails-templates/issues/155
Checkout this
use strict'
alert('route'); <----- is working
angular.module('core').config(['$stateProvider', '$urlRouterProvider', function ($stateProvider, $urlRouterProvider) {
// Redirect to 404 when route not found
$urlRouterProvider.otherwise(function ($injector, $location) {
$injector.get('$state').transitionTo('not-found', null, {
location: false
});
});
alert('inside route') <--- is working
// Home state routing
$stateProvider
.state('home', {
url: '/',
abstract: true,
templateUrl: 'players/layout/home.client.view.html',
controllerAs: 'vm',
controller: 'MasterController',
resolve: {
user_noti: function($http, $stateParams,jwtHelper, $window) {
alert('insde part') <--- not woking
if($window.user) {
return $http.get('/api/v1/notifications');
} else {
return [];
}
},
user_unconfrim_ticket: function($http, $stateParams,jwtHelper, $window){
if($window.user) {
return $http.get('/api/v1/tickets/unconfrim');
} else {
return [];
}
}
}
})
.state('home.index', {
url: '',
controllerAs: 'vm',
controller: 'HomeController',
data: {
ignoreState: true
},
templateUrl: 'players/home.client.view.html',
resolve: {
reward_data: function($http, $stateParams) {
return $http.get('/api/v1/rewards');
},
answers_data: function($http, $stateParams){
return $http.get('/api/v1/answers/current');
}
}
})
.state('home.game', {
url: 'game',
controller: 'GameController',
controllerAs: 'vm',
data: {
roles: ['player']
},
templateUrl: 'players/game/game.client.view.html'
});
}]);
And I put alert() in top of controller file is working and inside controller function is not working, I thought is not working since route can't detect the path
Any Sugesstion?
Update: I found actually problem, A real problem. if some state have resolve function it will be freeze ui. I don't know why because I never met before. I working with resolve many time only error form server will make resolve and ui will freeze. I ran "rails s -e production" is work normal but on real server not working

React Native - Navigate after an async action

I'm developing a mobile app with React Native and Redux and I'm facing a software design problem.
I want to call a REST API (async operation) for login and navigate to main view if that operation was successful.
I'm using redux and thunk so I already have the async actions implemented so my main doubt is: Where should I put the logic to navigate to main view?
Can I access the navigator object directly from an action and perform the navigation there?
Should I do that in the Login Component? (As I'm doing it already - check the code below).
componentWillReceiveProps(nextProps){
if(nextProps.errorLoginMsg){
Alert.alert("Login Failed", nextProps.errorLoginMsg);
}
else if(!nextProps.user.isNull()){
this.props.navigator.replace({name: 'main'});
}
}
I'm not confident of having that logic in the component. Does not seem a good practice. Are there any other way to do this?
Thanks
Here is the code how I do it:
const resetAction = NavigationActions.reset( {
index : 0,
actions: [
NavigationActions.navigate( { routeName: 'Home' } )
]
} );
this.props.requestDeleteEvent( {
id: eventID
} ).then( () => {
this.props.navigation.dispatch( resetAction );
} );
And inside function requestDeleteEvent:
export function requestDeleteEvent(requestData) {
const id = requestData.id;
return (dispatch, getState) => {
return fetch(Config.event + id, {
method: 'DELETE',
headers: {
'Content-Type': 'application/json; charset=UTF-8',
},
})
.then((response) => getResponseJson(response))
.then((responseJson) => {
if (responseJson.isSuccess) {
return dispatch(deleteEvent(id));
}
else {
return dispatch(triggerToast({type: 'alert', content: ERROR}));
}
}
);
}
}
This is one of the hardest problems in react native with the current Navigator API. I would suggest having a route store which holds the current route and have the component which includes the Navigator connected to this store and having a navigation triggered on componentWillReceiveProps.

Login Authentication with Devise (rails) & Angular

I currently have a mobile application where you can create issues, and view a list of issues others have created around your location.
The mobile app is is talking to a rails server and properly creating issues, and I have followed this guide covering Authentication with Rails & Devise.
In my controllers/app.js file, I have a local variable stored isLoggedIn that is set to false by default. When the application is loaded, I check to see whether the variable is true and if so, send the user to app.issues. Otherwise, the user is sent to app.auth.login.
$scope.$storage = $localStorage.$default({
isLoggedIn: false
});
$scope.$watch('$storage.isLoggedIn', function() {
if ($scope.$storage.isLoggedIn){
console.log('is logged in');
$state.go('app.issues');
}
else {
console.log('isnt logged in');
$state.go('app.auth.login');
}
});
Here is my root app.js file in my js folder.
angular.module('orangecone', ['ionic', 'orangecone.controllers', 'orangecone.services', 'ngCordova', 'ngStorage', 'ngResource'])
.run(function($ionicPlatform) {
$ionicPlatform.ready(function() {
// Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
// for form inputs)
if (window.cordova && window.cordova.plugins && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
cordova.plugins.Keyboard.disableScroll(true);
}
if (window.StatusBar) {
// org.apache.cordova.statusbar required
StatusBar.styleDefault();
}
});
})
.value('Constants', {
serverUrl: 'http://localhost:3000/'
})
.config(function($stateProvider, $urlRouterProvider, $httpProvider) {
$httpProvider.defaults.withCredentials = true;
$stateProvider
// setup an abstract state for the tabs directive
.state('app', {
url: '/app',
abstract: true,
templateUrl: 'templates/tabs.html'
})
.state('app.issues', {
url: '/issues',
views: {
'app-issues': {
templateUrl: 'templates/issues.html',
controller: 'IssuesCtrl'
}
}
})
.state('app.issue', {
url: '/issues/:issueId',
views: {
'app-issues': {
templateUrl: 'templates/issue.html',
controller: 'IssueCtrl'
}
}
})
.state('app.auth', {
url: '/auth',
abstract: true,
templateUrl: 'templates/auth/tabs.html'
})
.state('app.auth.login', {
url: '/login',
views: {
'login': {
templateUrl: 'templates/auth/login.html',
controller: 'AuthCtrl'
}
}
})
.state('app.auth.register', {
url: '/register',
views: {
'register': {
templateUrl: 'templates/auth/register.html',
controller: 'AuthCtrl'
}
}
})
// if none of the above states are matched, use this as the fallback
$urlRouterProvider.otherwise('/app/auth/login');
});
I have a waning feeling that I am overlooking something rather trivial. The application always console.logs logged in even though the rails server is wiped and there are no users in the system at all. The application should be redirecting the user to app/auth/login but never does. Whenever I type this URL into the browser it also redirects me to the app/issues page.
Any thoughts or opinions would be greatly appreciated.

Resources