with this code:
if (ionic.Platform.isIOS()) {
cordova.plugins.diagnostic.switchToSettings();
} else {
cordova.plugins.diagnostic.switchToLocationSettings();
}
I can open the native device configuration to mark the geolocation. but I do not know how to do it when the user turns on the geolocation, it simply executes that code but does not get an answer from that. I would like (if possible) to know if the user turned on the geolocation or not.
how can I do it?
I am using ionic1, although I suppose that the operation for this solution would apply to any version. thank you very much.
Unfortunately you can not get callback or response when user turn on/off location from device setting because there is no such way to communicate with Native settings.
But there is a workaround for this. Use isLocationEnabled() of cordova-diagnostic-plugin.
Below is complete working code:
$scope.$on("$ionicView.enter", function() {
cordova.plugins.diagnostic.isLocationEnabled(function(enabled) {
console.log("Location setting is " + (enabled ? "enabled" : "disabled"));
if (!enabled) {
var templateMsg = "Location is not enabled!\nDo you want to enable location service?"
var confirmPopup = $ionicPopup.confirm({
title: '<b>Location Service</b>',
template: '<input alert-enter-key style="position: absolute; left: -9999px;">' + templateMsg.replace(/\n/g, '<br>'),
okText: "Enable",
okType: 'ok-button',
cancelText: "Not now",
cancelType: 'cancel-button'
});
confirmPopup.then(function(res) {
if (res) {
if (ionic.Platform.isIOS()) {
if (window.cordova && window.cordova.plugins.settings) {
window.cordova.plugins.settings.open("settings", function() {
console.log('settings opened');
},
function() {
console.log('failed to open settings');
}
);
} else {
console.log('openNativeSettingsTest is not active!');
}
} else {
cordova.plugins.diagnostic.switchToLocationSettings();
} }
});
}
}, function(error) {
console.error("The following error occurred: " + error);
});
});
Note: To open location setting (Settings > Privacy > Location Services) on iOS there is plugin but There is change/ in iOS 11 platform due to which you can not open Settings > Privacy > Location Services.
Related
I'm using a script on my site to switch between chinese and english, It's a script i found in someones answer on stackoverflow.
This problem is, this script makes the users browser pop up a question "Blahblah.com wants to know your location. [Allow] [Block]" this is OK, but while it is showing that pop up, it is also displaying BOTH the languages divs and spans on the screen, so it is showing english div and right under it chinese div, How can I make it default to English language while the browser is asking for location?
the script is here:
$(function () {
///// Language Switching (2 languages: English and Chinese). /////
// Initially disable language switching button.
$('#switch-lang').css({'pointer-events':'none',
'cursor':'default'}).attr('disabled','disabled');
function langButtonListen() {
$('#switch-lang').on("click", function (event) {
event.preventDefault();
$('[lang="zh"]').toggle();
$('[lang="en"]').toggle();
// Switch cookie stored language.
if ($.cookie('lang') === 'en') {
$.cookie('lang', 'zh', { expires: 7 });
} else {
$.cookie('lang', 'en', { expires: 7 });
}
});
// Enable lang switching button.
$('#switch-lang').css({'pointer-events':'auto',
'cursor':'pointer'}).removeAttr('disabled');
}
// Check if language cookie already exists.
if ($.cookie('lang')) {
var lang = $.cookie('lang');
if (lang === 'en') {
$('[lang="zh"]').hide();
langButtonListen();
} else {
$('[lang="en"]').hide();
langButtonListen();
}
} else {
// no cookie set, so detect language based on location.
if ("geolocation" in navigator) {
// geolocation is available
navigator.geolocation.getCurrentPosition(function (position) {
// accepted geolocation so figure out which country
var lat = position.coords.latitude,
lng = position.coords.longitude;
$.getJSON('http://maps.googleapis.com/maps/api/geocode/json?latlng='+lat+','+lng+'&sensor=true', null, function (response) {
var country = response.results[response.results.length-1].formatted_address;
if (country === 'Taiwan' || country === 'China') {
$('[lang="en"]').hide();
$.cookie('lang', 'zh', { expires: 7 });
langButtonListen();
} else {
$('[lang="zh"]').hide();
$.cookie('lang', 'en', { expires: 7 });
langButtonListen();
}
}).fail(function (err) {
console.log('error: '+err);
$('[lang="zh"]').hide();
$.cookie('lang', 'en', { expires: 7 });
langButtonListen();
});
},
function (error) {
if (error.code == error.PERMISSION_DENIED) {
// denied geolocation
$('[lang="zh"]').hide();
$.cookie('lang', 'en', { expires: 7 });
langButtonListen();
} else {
console.log('Unknown error. Defaulting to English!');
$('[lang="zh"]').hide();
$.cookie('lang', 'en', { expires: 7 });
langButtonListen();
}
});
} else {
// geolocation IS NOT available
$('[lang="zh"]').hide();
$.cookie('lang', 'en', { expires: 7 });
langButtonListen();
}
}
});
I've tried various things involving this script and so far nothing is working. can anyone help to make it default to just show english while it is geolocating?
I tried to include a button (created from user event) on Sales order. Upon clicking it, Invoice will be generated. As soon as the button is hit, ther comes an error and invoice doesnt get generated. Can anyone help me with this?
//Client script
function pageInit() {
}
function csForButton(ctx) {
var rec = curr.get();
var customer = rec.getValue({ "fieldId": "customer" });
log.error({
title: 'customer',
details: customer
});
var scriptURL = url.resolveScript({
"scriptId": "customscript_button_task_sl",
"deploymentId": "customdeploy_button_task_sl"
});
console.log('scriptURL', scriptURL);
window.onbeforeunload = null;
window.open(scriptURL + '&id=' + rec.id);
}
return {
pageInit: pageInit,
csForButton: csForButton
};
//User Event Script
function beforeLoad(ctx) {
//if (context.type == context.UserEventType.VIEW) {
addbutton(ctx);
// }
}
function addbutton(ctx) {
try {
var rec = ctx.newRecord;//record object, now we can get its properties through it(e.g. fields)
var statusOfTrans = rec.getValue({ fieldId: 'status' });
log.error('statusOfTrans', statusOfTrans);
ctx.form.clientScriptFileId = "16474"
if (ctx.type == "view" && statusOfTrans == 'Pending Fulfillment') {
ctx.form.addButton({
id: 'custpage_make_invoice',
label: 'create invoice!',
functionName: 'csForButton'
});
}
}
catch (error) {
log.error('addbutton', error);
}
}
return {
beforeLoad: beforeLoad,
}
//Suitelet Script
function onRequest(ctx) {
try {
var req = ctx.request;
var res = ctx.response;
if (req.method == 'GET') {
var objRecord = rec.transform({
fromType: rec.Type.SALES_ORDER,
fromId: req.parameters.id,
toType: rec.Type.INVOICE,
isDynamic: true,
});
objRecord.save({
ignoreMandatoryFields: true
});
res.write({output: 'Invoice created'});
}
} catch (error) {
log.error('onRequest', error);
}
}
return {
'onRequest': onRequest
}
error (in suitelet):
{"type":"error.SuiteScriptError","name":"USER_ERROR","message":"You must enter at least one line item for this transaction.","stack":["anonymous(N/serverRecordService)","onRequest(/SuiteScripts/button SL.js:39)"],"cause":{"type":"internal error","code":"USER_ERROR","details":"You must enter at least one line item for this transaction.","userEvent":null,"stackTrace":["anonymous(N/serverRecordService)","onRequest(/SuiteScripts/button SL.js:39)"],"notifyOff":false},"id":"","notifyOff":false,"userFacing":false}
As Error says to include atleast 1 line but i wanted it to be generated automatically. I am new in suitescript and taking all the help from the documentation. Can anyone jst guide me what is wrong i m doing?
Thank u
You need the SO status to be Pending Billing. If the status of the SO is Pending Fulfillment, then no line items are ready to be invoiced.
I have a field that enables me to choose a folder from an electron dialog. On clicking the field, the dialog opens and I'm able to select the folder.
However, upon hitting ok, even though my model contains the folder's path, it does not reflect in the input field, until I click OUTSIDE the field (when it loses focus). How exactly do I fix this behaviour?
Template contains:
<input type="text" class="form-control" (click)="onClickPath($event)" [(ngModel)]="currentConfiguration.workspacePath" id="workspace-path" name="workspace-name" aria-label="workspace" aria-describedby="workspace-lable">
CurrentConfiguration.ts
export class CurrentConfiguration {
workspacePath: string;
}
configuation.component.ts
currentConfiguration: CurrentConfiguration = {
workspacePath: ""
};
//onClickedPath event:
onClickPath(event) {
console.log("clicked: ", event.target.id);
// open the dialog to select the directory
const dir = this.electronService.remote.dialog.showOpenDialog({
properties: ["openDirectory"],
title: event.target.id.split('-').join(" ")
}, (folderPath) => {
console.log(folderPath);
if (folderPath[0] == undefined) {
this.electronService.remote.dialog.showMessageBox({
type: "error",
buttons: ["ok"],
title: "Error",
message: "Please select the folder"
});
}
else{
// set the correct directoryPath.
this.currentConfiguration[event.target.id.split('-')[0] + 'Path'] = folderPath[0];
}
});
}
Note - this is a almost a dupe of This question Since it helped me resolve the issue, I'll post the answer.
Electron dialogs seem to function outside the angular zone and hence any updates to the data does no trigger angular to refresh the view.
In order to make the refresh happen, I had to execute the logic inside a zone like below:
import { NgZone } from '#angular/core';
...
...
currentConfiguration: CurrentConfiguration = {
workspacePath: ""
};
//onClickedPath event:
onClickPath(event) {
console.log("clicked: ", event.target.id);
// open the dialog to select the directory
const dir = this.electronService.remote.dialog.showOpenDialog({
properties: ["openDirectory"],
title: event.target.id.split('-').join(" ")
}, (folderPath) => {
console.log(folderPath);
if (folderPath[0] == undefined) {
this.electronService.remote.dialog.showMessageBox({
type: "error",
buttons: ["ok"],
title: "Error",
message: "Please select the folder"
});
}
else{
// run all of this inside the zone
this.zone.run(() => {
// set the correct directoryPath.
this.currentConfiguration[event.target.id.split('-')[0] + 'Path'] = folderPath[0];
}); // end of zone
}
});
}
I was using the below function to clear browser cache from the chrome extension :
function clearBrowsingData(callback, sinceTime) {
var dataSetToRemove = {
"appcache": true,
"cache": true
};
var removeOptions = {
"since": 0
}
if (sinceTime) {
removeOptions = {
"since": sinceTime
}
}
chrome.browsingData.remove(removeOptions, dataSetToRemove, function (data) {
if (chrome.runtime.lastError) {
// Something went wrong
console.warn("Whoops.. " + chrome.runtime.lastError.message);
// TODO: Show error to the user
return false;
} else {
callback(data);
}
});
}
But I need to do the same for the edge extension and I am not able to do it because chrome.browsingData.remove has been bridged in Edge . Can someone help me with an alternative to do the same?
I hope someone can help me with this.
I have a Backbone based SPA for a responsive website with a .net WebAPI providing all of the data.
I've recently found a weird problem. I've added a search box, which searches one of the catalogues on the system. This works fine on desktop browsers and on Android. On iOS, executing a search seems to take you back to the sign in page.
You can execute a search in various ways, you can either hit enter or you can click the search icon. Both of these then trigger a method that navigates the router to the URL for the search result.
My first thought was that it was some button weirdness, but I don't think that's the problem as both methods of search execution are causing the same problem.
The search results are displayed in a view that is secured (It requires a username to be present - this is stored in a hidden field on the page). There are two search boxes on the site - one on the home page and one on the search results page itself (it shows a default set when you load it first time - which it does load first time fine). Both search boxes are exhibiting the same behaviour.
My site is set up in such a way that when Backbone pulls back a model, if it gets a 401 back from the API then it will send you back to the login page, so I can only think it's happening here.
Here's my view code...
function (SiansPlan, ErrorManager, RecipeSearchResult, Header, Components, TemplateSource) {
var recipeSearchView = SiansPlan.SecureView.extend({
name: 'Recipe Search',
sectionName: 'Recipes',
queryText: '',
template: Handlebars.compile(TemplateSource),
headerView: new Header({ text: 'Recipes', swatch: 'e' }),
searchBoxRegion: undefined,
$searchWrapper: undefined,
$queryHeaderMobile: undefined,
$queryHeaderDesktop: undefined,
$searchButton: undefined,
$searchInput: undefined,
$recipeSearch : undefined,
events: {
'click .link-container': 'showRecipe',
'click #searchWrapper': 'showSearch',
'click #searchButton': 'showOrPerformSearch',
'keydown #searchButton': 'performSearchOnEnter',
'keydown #recipeSearch': 'performSearchOnEnter'
},
initialize: function (options) {
this.options = options || {};
SiansPlan.SecureView.prototype.initialize.call(this, options);
this.queryText = Object.exists(this.options.query) ? this.options.query : '';
},
bindData: function () {
this.$el.html(this.template({ results: this.collection.toJSON() }));
},
render: function () {
var that = this;
if (this.isSecured()) {
this.trigger('rendering');
var params = {
success: function () {
that.bindData();
that.trigger('rendered');
},
error: function (model, xhr) {
if (Object.exists(xhr) && xhr.status == 401) {
that.applyTimedOutSecureLoginPrompt();
} else {
that.$el.html('Unable to fetch search results');
ErrorManager.handleXhr('Search failed', xhr);
}
that.trigger('rendered');
}
};
if (!Object.exists(this.collection)) {
this.collection = new RecipeSearchResult.Collection({ username: SiansPlanApp.session.username(), query: this.queryText });
}
this.collection.fetch(params);
} else {
this.applySecureLoginPrompt();
}
return this;
},
postRender: function () {
var that = this;
var queryHeader = "All recipes";
if (Object.hasValue(this.queryText)) {
queryHeader = this.collection.length + " results for '" + this.queryText + "'";
}
this.$searchWrapper = $('#searchWrapper');
this.$queryHeaderMobile = $('#queryHeaderMobile');
this.$queryHeaderDesktop = $('#queryHeaderDesktop');
this.$searchButton = $('#searchWrapper');
this.$searchInput = $('#searchInput');
this.$recipeSearch = $('#recipeSearch');
this.$queryHeaderMobile.html(queryHeader);
this.$queryHeaderDesktop.html(queryHeader);
this.$recipeSearch.val(this.queryText);
SiansPlanApp.session.waitForLoad(30, function () {
that.searchBoxRegion = new SiansPlan.Region({ el: '.recipe-search-box-container' });
that.searchBoxRegion.renderView(new Components.RecipeSearchBox({ username: SiansPlanApp.session.username(), query: that.queryText, title: 'Search' }));
});
},
performSearchOnEnter: function (e) {
if (e.keyCode == 13) {
this.showOrPerformSearch(e);
}
},
showOrPerformSearch: function (e) {
if (!this.$searchInput.is(':visible')) {
this.showSearch(e);
} else {
e.preventDefault();
var url = '/recipes/search/' + this.$recipeSearch.val();
window.SiansPlanApp.router.navigate(url, true);
}
return false;
},
showRecipe: function (e) {
e.preventDefault();
var url = $(e.target).find('a').first().attr('href');
window.SiansPlanApp.router.navigate(url, true);
},
showSearch: function (e) {
e.preventDefault();
if (!this.$searchInput.is(':visible')) {
this.$queryHeaderMobile.hide();
this.$searchInput.show();
this.$recipeSearch.focus();
this.$recipeSearch.select();
}
return false;
}
});
return recipeSearchView;
});
UPDATES
I've set up some alerts as follows in the script to see what's going on and I've discovered the following...
render: function () {
var that = this;
if (this.isSecured()) {
this.trigger('rendering');
var params = {
success: function () {
alert('Bind has succeeded!');
that.bindData();
that.trigger('rendered');
},
error: function (model, xhr) {
alert('Bind has failed!');
if (Object.exists(xhr) && xhr.status == 401) {
that.applyTimedOutSecureLoginPrompt();
} else {
that.$el.html('Unable to fetch search results');
ErrorManager.handleXhr('Search failed', xhr);
}
that.trigger('rendered');
alert(xhr.status + ' ' + xhr.responseText);
}
};
if (!Object.exists(this.collection)) {
alert('Binding new collection: ' + SiansPlanApp.session.username() + ' - ' + this.queryText);
this.collection = new RecipeSearchResult.Collection({ username: SiansPlanApp.session.username(), query: this.queryText });
}
alert('About to fetch using ' + this.collection.url());
this.collection.fetch(params);
} else {
alert('I dont appear to be secured??');
this.applySecureLoginPrompt();
}
return this;
},
When I first load the page (to show all the results) it loads fine and 'Bind Succeeded!' appears. The API call made is /api/recipes/search/{username}/
When I submit search criteria it fails ('Bind failed!') with the API call of /api/recipes/search/{username}/{query} and returns a 401.
This has me even more befuddled than before as this now looks like an API issue, but other devices are working fine and if I submit the same queries into Fiddler everything is, as expected, fine.
I've found the answer in the smallest place...
The issue was that the search criteria had an upper case letter. So, for example, when searching with 'Fish', The API generated a 301 which redirected to /api/recipes/search/{username}/fish. iOS didn't like that and reported it as a 401 (Which truly sucks!)