@nota/nativescript-webview-ext
Version:
Extended WebView for NativeScript which adds 'x-local' scheme for local-files. events between WebView and native-layer, javascript execution, injecting CSS and JS-files.
1,120 lines • 146 kB
JavaScript
"use strict";
function __export(m) {
for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
}
Object.defineProperty(exports, "__esModule", { value: true });
var fs = require("@nativescript/core/file-system");
var view_1 = require("@nativescript/core/ui/core/view");
var view_2 = require("tns-core-modules/ui/core/view/view");
var URL = require("url");
var nativescript_webview_bridge_loader_1 = require("./nativescript-webview-bridge-loader");
__export(require("@nativescript/core/ui/core/view"));
exports.autoInjectJSBridgeProperty = new view_1.Property({
name: "autoInjectJSBridge",
defaultValue: true,
valueConverter: view_1.booleanConverter,
});
exports.builtInZoomControlsProperty = new view_1.Property({
name: "builtInZoomControls",
defaultValue: true,
valueConverter: view_1.booleanConverter,
});
exports.cacheModeProperty = new view_1.Property({
name: "cacheMode",
defaultValue: "default",
});
exports.databaseStorageProperty = new view_1.Property({
name: "databaseStorage",
defaultValue: false,
valueConverter: view_1.booleanConverter,
});
exports.domStorageProperty = new view_1.Property({
name: "domStorage",
defaultValue: false,
valueConverter: view_1.booleanConverter,
});
exports.debugModeProperty = new view_1.Property({
name: "debugMode",
defaultValue: false,
valueConverter: view_1.booleanConverter,
});
exports.displayZoomControlsProperty = new view_1.Property({
name: "displayZoomControls",
defaultValue: true,
valueConverter: view_1.booleanConverter,
});
exports.supportZoomProperty = new view_1.Property({
name: "supportZoom",
defaultValue: false,
valueConverter: view_1.booleanConverter,
});
exports.srcProperty = new view_1.Property({
name: "src",
});
exports.scrollBounceProperty = new view_1.Property({
name: "scrollBounce",
valueConverter: view_1.booleanConverter,
});
exports.viewPortProperty = new view_1.Property({
name: "viewPortSize",
defaultValue: false,
valueConverter: function (value) {
var e_1, _a;
var defaultViewPort = {
initialScale: 1.0,
};
var valueLowerCaseStr = ("" + (value || "")).toLowerCase();
if (valueLowerCaseStr === "false") {
return false;
}
else if (valueLowerCaseStr === "true" || valueLowerCaseStr === "") {
return defaultViewPort;
}
var viewPortInputValues = __assign({}, defaultViewPort);
if (typeof value === "object") {
viewPortInputValues = __assign({}, value);
}
else if (typeof value === "string") {
try {
viewPortInputValues = JSON.parse(value);
}
catch (err) {
try {
for (var _b = __values(value.split(",").map(function (v) { return v.trim(); })), _c = _b.next(); !_c.done; _c = _b.next()) {
var part = _c.value;
if (!part) {
continue;
}
var _d = __read(part.split("=").map(function (v) { return v.trim(); }), 2), key = _d[0], v = _d[1];
if (!key || !v) {
continue;
}
var lcValue = ("" + v).toLowerCase();
switch (key) {
case "user-scalable":
case "userScalable": {
switch (lcValue) {
case "yes":
case "true": {
viewPortInputValues.userScalable = true;
break;
}
case "no":
case "false": {
viewPortInputValues.userScalable = false;
break;
}
}
break;
}
case "width": {
if (lcValue === "device-width") {
viewPortInputValues.width = "device-width";
}
else {
viewPortInputValues.width = Number(v);
}
break;
}
case "height": {
if (lcValue === "device-height") {
viewPortInputValues.height = "device-height";
}
else {
viewPortInputValues.height = Number(v);
}
break;
}
case "minimumScale":
case "minimum-scale": {
viewPortInputValues.minimumScale = Number(v);
break;
}
case "maximumScale":
case "maximum-scale": {
viewPortInputValues.maximumScale = Number(v);
break;
}
case "initialScale":
case "initial-scale": {
viewPortInputValues.initialScale = Number(v);
break;
}
}
}
}
catch (e_1_1) { e_1 = { error: e_1_1 }; }
finally {
try {
if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
}
finally { if (e_1) throw e_1.error; }
}
}
}
var _e = viewPortInputValues.initialScale, initialScale = _e === void 0 ? defaultViewPort.initialScale : _e, width = viewPortInputValues.width, height = viewPortInputValues.height, userScalable = viewPortInputValues.userScalable, minimumScale = viewPortInputValues.minimumScale, maximumScale = viewPortInputValues.maximumScale;
return {
initialScale: initialScale,
width: width,
height: height,
userScalable: userScalable,
minimumScale: minimumScale,
maximumScale: maximumScale,
};
},
});
var EventNames;
(function (EventNames) {
EventNames["LoadFinished"] = "loadFinished";
EventNames["LoadProgress"] = "loadProgress";
EventNames["LoadStarted"] = "loadStarted";
EventNames["ShouldOverrideUrlLoading"] = "shouldOverrideUrlLoading";
EventNames["TitleChanged"] = "titleChange";
EventNames["WebAlert"] = "webAlert";
EventNames["WebConfirm"] = "webConfirm";
EventNames["WebConsole"] = "webConsole";
EventNames["EnterFullscreen"] = "enterFullscreen";
EventNames["ExitFullscreen"] = "exitFullscreen";
EventNames["WebPrompt"] = "webPrompt";
})(EventNames = exports.EventNames || (exports.EventNames = {}));
var UnsupportedSDKError = (function (_super) {
__extends(UnsupportedSDKError, _super);
function UnsupportedSDKError(minSdk) {
var _this = _super.call(this, "Android API < " + minSdk + " not supported") || this;
Object.setPrototypeOf(_this, UnsupportedSDKError.prototype);
return _this;
}
return UnsupportedSDKError;
}(Error));
exports.UnsupportedSDKError = UnsupportedSDKError;
var WebViewExtBase = (function (_super) {
__extends(WebViewExtBase, _super);
function WebViewExtBase() {
var _this = _super !== null && _super.apply(this, arguments) || this;
_this.autoInjectJSBridge = true;
_this.autoInjectScriptFiles = [];
_this.autoInjectStyleSheetFiles = [];
_this.autoInjectJavaScriptBlocks = [];
_this.tempSuspendSrcLoading = false;
return _this;
}
WebViewExtBase_1 = WebViewExtBase;
Object.defineProperty(WebViewExtBase.prototype, "interceptScheme", {
get: function () {
return "x-local";
},
enumerable: true,
configurable: true
});
Object.defineProperty(WebViewExtBase, "loadStartedEvent", {
get: function () {
return EventNames.LoadStarted;
},
enumerable: true,
configurable: true
});
Object.defineProperty(WebViewExtBase, "loadFinishedEvent", {
get: function () {
return EventNames.LoadFinished;
},
enumerable: true,
configurable: true
});
Object.defineProperty(WebViewExtBase, "shouldOverrideUrlLoadingEvent", {
get: function () {
return EventNames.ShouldOverrideUrlLoading;
},
enumerable: true,
configurable: true
});
Object.defineProperty(WebViewExtBase, "loadProgressEvent", {
get: function () {
return EventNames.LoadProgress;
},
enumerable: true,
configurable: true
});
Object.defineProperty(WebViewExtBase, "titleChangedEvent", {
get: function () {
return EventNames.TitleChanged;
},
enumerable: true,
configurable: true
});
Object.defineProperty(WebViewExtBase, "webAlertEvent", {
get: function () {
return EventNames.WebAlert;
},
enumerable: true,
configurable: true
});
Object.defineProperty(WebViewExtBase, "webConfirmEvent", {
get: function () {
return EventNames.WebConfirm;
},
enumerable: true,
configurable: true
});
Object.defineProperty(WebViewExtBase, "webPromptEvent", {
get: function () {
return EventNames.WebPrompt;
},
enumerable: true,
configurable: true
});
Object.defineProperty(WebViewExtBase, "webConsoleEvent", {
get: function () {
return EventNames.WebConsole;
},
enumerable: true,
configurable: true
});
Object.defineProperty(WebViewExtBase, "enterFullscreenEvent", {
get: function () {
return EventNames.EnterFullscreen;
},
enumerable: true,
configurable: true
});
Object.defineProperty(WebViewExtBase, "exitFullscreenEvent", {
get: function () {
return EventNames.ExitFullscreen;
},
enumerable: true,
configurable: true
});
WebViewExtBase.prototype._onLoadFinished = function (url, error) {
return __awaiter(this, void 0, void 0, function () {
var args, error_1;
var _this = this;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
url = this.normalizeURL(url);
if (!error) {
try {
this.tempSuspendSrcLoading = true;
this.src = url;
this.tempSuspendSrcLoading = false;
}
finally {
this.tempSuspendSrcLoading = false;
}
}
args = {
error: error,
eventName: WebViewExtBase_1.loadFinishedEvent,
navigationType: undefined,
object: this,
url: url,
};
if (error) {
this.notify(args);
return [2, Promise.reject(args)];
}
this.writeTrace("WebViewExt._onLoadFinished(\"" + url + "\", " + (error || void 0) + ") - > Injecting webview-bridge JS code");
if (!this.autoInjectJSBridge) {
return [2, Promise.resolve(args)];
}
_a.label = 1;
case 1:
_a.trys.push([1, 6, , 7]);
return [4, this.injectWebViewBridge()];
case 2:
_a.sent();
return [4, this.loadJavaScriptFiles(this.autoInjectScriptFiles)];
case 3:
_a.sent();
return [4, this.loadStyleSheetFiles(this.autoInjectStyleSheetFiles)];
case 4:
_a.sent();
return [4, this.executePromises(this.autoInjectJavaScriptBlocks.map(function (data) { return data.scriptCode; }), -1)];
case 5:
_a.sent();
return [3, 7];
case 6:
error_1 = _a.sent();
args.error = error_1;
return [3, 7];
case 7:
this.notify(args);
this.getTitle().then(function (title) { return title && _this._titleChanged(title); });
return [2, args];
}
});
});
};
WebViewExtBase.prototype._onLoadStarted = function (url, navigationType) {
var args = {
eventName: WebViewExtBase_1.loadStartedEvent,
navigationType: navigationType,
object: this,
url: url,
};
this.notify(args);
};
WebViewExtBase.prototype._onShouldOverrideUrlLoading = function (url, httpMethod, navigationType) {
var args = {
eventName: WebViewExtBase_1.shouldOverrideUrlLoadingEvent,
httpMethod: httpMethod,
navigationType: navigationType,
object: this,
url: url,
};
this.notify(args);
var eventNameWithSpellingError = "shouldOverideUrlLoading";
if (this.hasListeners(eventNameWithSpellingError)) {
console.error("eventName '" + eventNameWithSpellingError + "' is deprecated due to spelling error:\nPlease use: " + WebViewExtBase_1.shouldOverrideUrlLoadingEvent);
var argsWithSpellingError = __assign({}, args, { eventName: eventNameWithSpellingError });
this.notify(argsWithSpellingError);
if (argsWithSpellingError.cancel) {
return argsWithSpellingError.cancel;
}
}
return args.cancel;
};
WebViewExtBase.prototype._loadProgress = function (progress) {
var args = {
eventName: WebViewExtBase_1.loadProgressEvent,
object: this,
progress: progress,
url: this.src,
};
this.notify(args);
};
WebViewExtBase.prototype._titleChanged = function (title) {
var args = {
eventName: WebViewExtBase_1.titleChangedEvent,
object: this,
title: title,
url: this.src,
};
this.notify(args);
};
WebViewExtBase.prototype._webAlert = function (message, callback) {
if (!this.hasListeners(WebViewExtBase_1.webAlertEvent)) {
return false;
}
var args = {
eventName: WebViewExtBase_1.webAlertEvent,
object: this,
message: message,
url: this.src,
callback: callback,
};
this.notify(args);
return true;
};
WebViewExtBase.prototype._webConfirm = function (message, callback) {
if (!this.hasListeners(WebViewExtBase_1.webConfirmEvent)) {
return false;
}
var args = {
eventName: WebViewExtBase_1.webConfirmEvent,
object: this,
message: message,
url: this.src,
callback: callback,
};
this.notify(args);
return true;
};
WebViewExtBase.prototype._webPrompt = function (message, defaultText, callback) {
if (!this.hasListeners(WebViewExtBase_1.webPromptEvent)) {
return false;
}
var args = {
eventName: WebViewExtBase_1.webPromptEvent,
object: this,
message: message,
defaultText: defaultText,
url: this.src,
callback: callback,
};
this.notify(args);
return true;
};
WebViewExtBase.prototype._webConsole = function (message, lineNo, level) {
if (!this.hasListeners(WebViewExtBase_1.webConsoleEvent)) {
return false;
}
var args = {
eventName: WebViewExtBase_1.webConsoleEvent,
object: this,
data: {
message: message,
lineNo: lineNo,
level: level,
},
url: this.src,
};
this.notify(args);
return true;
};
WebViewExtBase.prototype._onEnterFullscreen = function (exitFullscreen) {
if (!this.hasListeners(WebViewExtBase_1.enterFullscreenEvent)) {
return false;
}
var args = {
eventName: WebViewExtBase_1.enterFullscreenEvent,
object: this,
exitFullscreen: exitFullscreen,
url: this.src,
};
this.notify(args);
return true;
};
WebViewExtBase.prototype._onExitFullscreen = function () {
var args = {
eventName: WebViewExtBase_1.exitFullscreenEvent,
object: this,
url: this.src,
};
this.notify(args);
return true;
};
WebViewExtBase.prototype._loadUrl = function (src) {
throw new Error("Method not implemented.");
};
WebViewExtBase.prototype._loadData = function (src) {
throw new Error("Method not implemented.");
};
WebViewExtBase.prototype.stopLoading = function () {
throw new Error("Method not implemented.");
};
Object.defineProperty(WebViewExtBase.prototype, "canGoBack", {
get: function () {
throw new Error("This member is abstract.");
},
enumerable: true,
configurable: true
});
Object.defineProperty(WebViewExtBase.prototype, "canGoForward", {
get: function () {
throw new Error("This member is abstract.");
},
enumerable: true,
configurable: true
});
WebViewExtBase.prototype.goBack = function () {
throw new Error("Method not implemented.");
};
WebViewExtBase.prototype.goForward = function () {
throw new Error("Method not implemented.");
};
WebViewExtBase.prototype.reload = function () {
throw new Error("Method not implemented.");
};
WebViewExtBase.prototype[exports.srcProperty.getDefault] = function () {
return "";
};
WebViewExtBase.prototype[exports.srcProperty.setNative] = function (src) {
if (!src || this.tempSuspendSrcLoading) {
return;
}
var originSrc = src;
this.stopLoading();
if (src.startsWith("~/")) {
src = "file://" + fs.knownFolders.currentApp().path + "/" + src.substr(2);
this.writeTrace("WebViewExt.src = \"" + originSrc + "\" startsWith ~/ resolved to \"" + src + "\"");
}
else if (src.startsWith("/")) {
src = "file://" + src;
this.writeTrace("WebViewExt.src = \"" + originSrc + "\" startsWith \"/\" resolved to " + src);
}
var lcSrc = src.toLowerCase();
if (lcSrc.startsWith("file:///")) {
src = encodeURI(src);
if (lcSrc !== src) {
this.writeTrace("WebViewExt.src = \"" + originSrc + "\" escaped to \"" + src + "\"");
}
}
if (lcSrc.startsWith(this.interceptScheme) || lcSrc.startsWith("http://") || lcSrc.startsWith("https://") || lcSrc.startsWith("file:///")) {
src = this.normalizeURL(src);
if (originSrc !== src) {
try {
this.tempSuspendSrcLoading = true;
this.src = src;
}
catch (_a) {
}
finally {
this.tempSuspendSrcLoading = false;
}
}
this._loadUrl(src);
this.writeTrace("WebViewExt.src = \"" + originSrc + "\" - LoadUrl(\"" + src + "\")");
}
else {
this._loadData(src);
this.writeTrace("WebViewExt.src = \"" + originSrc + "\" - LoadData(\"" + src + "\")");
}
};
WebViewExtBase.prototype[exports.viewPortProperty.setNative] = function (value) {
if (this.src) {
this.injectViewPortMeta();
}
};
WebViewExtBase.prototype.resolveLocalResourceFilePath = function (filepath) {
if (!filepath) {
this.writeTrace("WebViewExt.resolveLocalResourceFilePath() no filepath", view_1.traceMessageType.error);
return;
}
if (filepath.startsWith("~")) {
filepath = fs.path.normalize(fs.knownFolders.currentApp().path + filepath.substr(1));
}
if (filepath.startsWith("file://")) {
filepath = filepath.replace(/^file:\/\//, "");
}
if (!fs.File.exists(filepath)) {
this.writeTrace("WebViewExt.resolveLocalResourceFilePath(\"" + filepath + "\") - no such file", view_1.traceMessageType.error);
return;
}
return filepath;
};
WebViewExtBase.prototype.registerLocalResource = function (name, filepath) {
throw new Error("Method not implemented.");
};
WebViewExtBase.prototype.unregisterLocalResource = function (name) {
throw new Error("Method not implemented.");
};
WebViewExtBase.prototype.getRegisteredLocalResource = function (name) {
throw new Error("Method not implemented.");
};
WebViewExtBase.prototype.loadUrl = function (src) {
var _this = this;
if (!src) {
return this._onLoadFinished(src, "empty src");
}
return new Promise(function (resolve, reject) {
var loadFinishedEvent = function (args) {
_this.off(WebViewExtBase_1.loadFinishedEvent, loadFinishedEvent);
if (args.error) {
reject(args);
}
else {
resolve(args);
}
};
_this.on(WebViewExtBase_1.loadFinishedEvent, loadFinishedEvent);
_this.src = src;
});
};
WebViewExtBase.prototype.loadJavaScriptFile = function (scriptName, filepath) {
return this.loadJavaScriptFiles([
{
resourceName: scriptName,
filepath: filepath,
},
]);
};
WebViewExtBase.prototype.loadJavaScriptFiles = function (files) {
return __awaiter(this, void 0, void 0, function () {
var promiseScriptCodes, files_1, files_1_1, _a, resourceName, filepath, scriptCode, _b;
var e_2, _c;
return __generator(this, function (_d) {
switch (_d.label) {
case 0:
if (!files || !files.length) {
return [2];
}
promiseScriptCodes = [];
try {
for (files_1 = __values(files), files_1_1 = files_1.next(); !files_1_1.done; files_1_1 = files_1.next()) {
_a = files_1_1.value, resourceName = _a.resourceName, filepath = _a.filepath;
scriptCode = this.generateLoadJavaScriptFileScriptCode(resourceName, filepath);
promiseScriptCodes.push(scriptCode);
this.writeTrace("WebViewExt.loadJavaScriptFiles() - > Loading javascript file: \"" + filepath + "\"");
}
}
catch (e_2_1) { e_2 = { error: e_2_1 }; }
finally {
try {
if (files_1_1 && !files_1_1.done && (_c = files_1.return)) _c.call(files_1);
}
finally { if (e_2) throw e_2.error; }
}
if (promiseScriptCodes.length !== files.length) {
this.writeTrace("WebViewExt.loadJavaScriptFiles() - > Num of generated scriptCodes " + promiseScriptCodes.length + " differ from num files " + files.length, view_1.traceMessageType.error);
}
if (!promiseScriptCodes.length) {
this.writeTrace("WebViewExt.loadJavaScriptFiles() - > No files");
return [2];
}
if (!promiseScriptCodes.length) {
return [2];
}
_b = this.executePromises;
return [4, Promise.all(promiseScriptCodes)];
case 1: return [4, _b.apply(this, [_d.sent()])];
case 2:
_d.sent();
return [2];
}
});
});
};
WebViewExtBase.prototype.loadStyleSheetFile = function (stylesheetName, filepath, insertBefore) {
if (insertBefore === void 0) { insertBefore = true; }
return this.loadStyleSheetFiles([
{
resourceName: stylesheetName,
filepath: filepath,
insertBefore: insertBefore,
},
]);
};
WebViewExtBase.prototype.loadStyleSheetFiles = function (files) {
return __awaiter(this, void 0, void 0, function () {
var promiseScriptCodes, files_2, files_2_1, _a, resourceName, filepath, insertBefore, scriptCode, _b;
var e_3, _c;
return __generator(this, function (_d) {
switch (_d.label) {
case 0:
if (!files || !files.length) {
return [2];
}
promiseScriptCodes = [];
try {
for (files_2 = __values(files), files_2_1 = files_2.next(); !files_2_1.done; files_2_1 = files_2.next()) {
_a = files_2_1.value, resourceName = _a.resourceName, filepath = _a.filepath, insertBefore = _a.insertBefore;
scriptCode = this.generateLoadCSSFileScriptCode(resourceName, filepath, insertBefore);
promiseScriptCodes.push(scriptCode);
}
}
catch (e_3_1) { e_3 = { error: e_3_1 }; }
finally {
try {
if (files_2_1 && !files_2_1.done && (_c = files_2.return)) _c.call(files_2);
}
finally { if (e_3) throw e_3.error; }
}
if (promiseScriptCodes.length !== files.length) {
this.writeTrace("WebViewExt.loadStyleSheetFiles() - > Num of generated scriptCodes " + promiseScriptCodes.length + " differ from num files " + files.length, view_1.traceMessageType.error);
}
if (!promiseScriptCodes.length) {
this.writeTrace("WebViewExt.loadStyleSheetFiles() - > No files");
return [2];
}
_b = this.executePromises;
return [4, Promise.all(promiseScriptCodes)];
case 1: return [4, _b.apply(this, [_d.sent()])];
case 2:
_d.sent();
return [2];
}
});
});
};
WebViewExtBase.prototype.autoLoadJavaScriptFile = function (resourceName, filepath) {
if (this.src) {
this.loadJavaScriptFile(resourceName, filepath).catch(function () { return void 0; });
}
this.autoInjectScriptFiles.push({ resourceName: resourceName, filepath: filepath });
};
WebViewExtBase.prototype.removeAutoLoadJavaScriptFile = function (resourceName) {
this.autoInjectScriptFiles = this.autoInjectScriptFiles.filter(function (data) { return data.resourceName !== resourceName; });
};
WebViewExtBase.prototype.autoLoadStyleSheetFile = function (resourceName, filepath, insertBefore) {
if (this.src) {
this.loadStyleSheetFile(resourceName, filepath, insertBefore).catch(function () { return void 0; });
}
this.autoInjectStyleSheetFiles.push({
resourceName: resourceName,
filepath: filepath,
insertBefore: insertBefore,
});
};
WebViewExtBase.prototype.removeAutoLoadStyleSheetFile = function (resourceName) {
this.autoInjectStyleSheetFiles = this.autoInjectStyleSheetFiles.filter(function (data) { return data.resourceName !== resourceName; });
};
WebViewExtBase.prototype.autoExecuteJavaScript = function (scriptCode, name) {
if (this.src) {
this.executePromise(scriptCode).catch(function () { return void 0; });
}
this.removeAutoExecuteJavaScript(name);
var fixedCodeBlock = scriptCode.trim();
this.autoInjectJavaScriptBlocks.push({
scriptCode: fixedCodeBlock,
name: name,
});
};
WebViewExtBase.prototype.removeAutoExecuteJavaScript = function (name) {
this.autoInjectJavaScriptBlocks = this.autoInjectJavaScriptBlocks.filter(function (data) { return data.name !== name; });
};
WebViewExtBase.prototype.normalizeURL = function (url) {
if (!url) {
return url;
}
if (url.startsWith(this.interceptScheme)) {
return url;
}
return URL.parse(url).format();
};
WebViewExtBase.prototype.ensureFetchSupport = function () {
return __awaiter(this, void 0, void 0, function () {
var _a;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
if (WebViewExtBase_1.isFetchSupported) {
return [2, Promise.resolve()];
}
if (!(typeof WebViewExtBase_1.isFetchSupported === "undefined")) return [3, 2];
this.writeTrace("WebViewExtBase.ensureFetchSupport() - need to check for fetch support.");
_a = WebViewExtBase_1;
return [4, this.executeJavaScript("typeof fetch !== 'undefined'")];
case 1:
_a.isFetchSupported = _b.sent();
_b.label = 2;
case 2:
if (WebViewExtBase_1.isFetchSupported) {
this.writeTrace("WebViewExtBase.ensureFetchSupport() - fetch is supported - polyfill not needed.");
return [2];
}
this.writeTrace("WebViewExtBase.ensureFetchSupport() - fetch is not supported - polyfill needed.");
return [4, this.loadFetchPolyfill()];
case 3: return [2, _b.sent()];
}
});
});
};
WebViewExtBase.prototype.loadFetchPolyfill = function () {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4, this.executeJavaScript(nativescript_webview_bridge_loader_1.fetchPolyfill, false)];
case 1:
_a.sent();
return [2];
}
});
});
};
WebViewExtBase.prototype.ensurePromiseSupport = function () {
return __awaiter(this, void 0, void 0, function () {
var _a;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
if (WebViewExtBase_1.isPromiseSupported) {
return [2];
}
if (!(typeof WebViewExtBase_1.isPromiseSupported === "undefined")) return [3, 2];
this.writeTrace("WebViewExtBase.ensurePromiseSupport() - need to check for promise support.");
_a = WebViewExtBase_1;
return [4, this.executeJavaScript("typeof Promise !== 'undefined'")];
case 1:
_a.isPromiseSupported = _b.sent();
_b.label = 2;
case 2:
if (WebViewExtBase_1.isPromiseSupported) {
this.writeTrace("WebViewExtBase.ensurePromiseSupport() - promise is supported - polyfill not needed.");
return [2];
}
this.writeTrace("WebViewExtBase.ensurePromiseSupport() - promise is not supported - polyfill needed.");
return [4, this.loadPromisePolyfill()];
case 3:
_b.sent();
return [2];
}
});
});
};
WebViewExtBase.prototype.loadPromisePolyfill = function () {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4, this.executeJavaScript(nativescript_webview_bridge_loader_1.promisePolyfill, false)];
case 1:
_a.sent();
return [2];
}
});
});
};
WebViewExtBase.prototype.ensurePolyfills = function () {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4, this.ensurePromiseSupport()];
case 1:
_a.sent();
return [4, this.ensureFetchSupport()];
case 2:
_a.sent();
return [2];
}
});
});
};
WebViewExtBase.prototype.executeJavaScript = function (scriptCode, stringifyResult) {
throw new Error("Method not implemented.");
};
WebViewExtBase.prototype.executePromise = function (scriptCode, timeout) {
if (timeout === void 0) { timeout = 2000; }
return __awaiter(this, void 0, void 0, function () {
var results;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4, this.executePromises([scriptCode], timeout)];
case 1:
results = _a.sent();
return [2, results && results[0]];
}
});
});
};
WebViewExtBase.prototype.executePromises = function (scriptCodes, timeout) {
if (timeout === void 0) { timeout = 2000; }
return __awaiter(this, void 0, void 0, function () {
var reqId, eventName, scriptHeader, scriptBody, scriptCodes_1, scriptCodes_1_1, scriptCode_1, scriptFooter, scriptCode, promiseScriptCode;
var e_4, _a;
var _this = this;
return __generator(this, function (_b) {
if (scriptCodes.length === 0) {
return [2];
}
reqId = "" + Math.round(Math.random() * 1000);
eventName = "tmp-promise-event-" + reqId;
scriptHeader = "\n var promises = [];\n var p = Promise.resolve();\n ".trim();
scriptBody = [];
try {
for (scriptCodes_1 = __values(scriptCodes), scriptCodes_1_1 = scriptCodes_1.next(); !scriptCodes_1_1.done; scriptCodes_1_1 = scriptCodes_1.next()) {
scriptCode_1 = scriptCodes_1_1.value;
if (!scriptCode_1) {
continue;
}
if (typeof scriptCode_1 !== "string") {
this.writeTrace("WebViewExt.executePromises() - scriptCode is not a string");
continue;
}
scriptBody.push(("\n p = p.then(function() {\n return " + scriptCode_1.trim() + ";\n });\n\n promises.push(p);\n ").trim());
}
}
catch (e_4_1) { e_4 = { error: e_4_1 }; }
finally {
try {
if (scriptCodes_1_1 && !scriptCodes_1_1.done && (_a = scriptCodes_1.return)) _a.call(scriptCodes_1);
}
finally { if (e_4) throw e_4.error; }
}
scriptFooter = "\n return Promise.all(promises);\n ".trim();
scriptCode = ("(function() {\n " + scriptHeader + "\n " + scriptBody.join(";") + "\n " + scriptFooter + "\n })()").trim();
promiseScriptCode = ("\n (function() {\n var eventName = " + JSON.stringify(eventName) + ";\n try {\n var promise = (function() {return " + scriptCode + "})();\n window.nsWebViewBridge.executePromise(promise, eventName);\n } catch (err) {\n window.nsWebViewBridge.emitError(err, eventName);\n }\n })();\n ").trim();
return [2, new Promise(function (resolve, reject) {
var timer;
var tmpPromiseEvent = function (args) {
var e_5, _a;
clearTimeout(timer);
var _b = args.data || {}, data = _b.data, err = _b.err;
if (typeof err === "undefined") {
resolve(data);
return;
}
if (err && typeof err === "object") {
var error = new Error(err.message || err.name || err);
if (err.stack) {
error.webStack = err.stack;
}
try {
for (var _c = __values(Object.entries(err)), _d = _c.next(); !_d.done; _d = _c.next()) {
var _e = __read(_d.value, 2), key = _e[0], value = _e[1];
if (key in error) {
continue;
}
error[key] = value;
}
}
catch (e_5_1) { e_5 = { error: e_5_1 }; }
finally {
try {
if (_d && !_d.done && (_a = _c.return)) _a.call(_c);
}
finally { if (e_5) throw e_5.error; }
}
reject(error);
return;
}
reject(new Error(err));
};
_this.once(eventName, tmpPromiseEvent);
_this.executeJavaScript(promiseScriptCode, false);
if (timeout > 0) {
timer = setTimeout(function () {
reject(new Error("Timed out after: " + timeout));
_this.off(eventName);
}, timeout);
}
})];
});
});
};
WebViewExtBase.prototype.generateLoadJavaScriptFileScriptCode = function (resourceName, path) {
return __awaiter(this, void 0, void 0, function () {
var fixedResourceName, scriptHref, elId, scriptCode;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
if (!this.supportXLocalScheme) return [3, 1];
fixedResourceName = this.fixLocalResourceName(resourceName);
if (path) {
this.registerLocalResource(fixedResourceName, path);
}
scriptHref = this.interceptScheme + "://" + fixedResourceName;
return [2, "window.nsWebViewBridge.injectJavaScriptFile(" + JSON.stringify(scriptHref) + ");"];
case 1:
elId = resourceName.replace(/^[:]*:\/\//, "").replace(/[^a-z0-9]/g, "");
return [4, fs.File.fromPath(this.resolveLocalResourceFilePath(path)).readText()];
case 2:
scriptCode = _a.sent();
return [2, "window.nsWebViewBridge.injectJavaScript(" + JSON.stringify(elId) + ", " + scriptCode + ");"];
}
});
});
};
WebViewExtBase.prototype.generateLoadCSSFileScriptCode = function (resourceName, path, insertBefore) {
if (insertBefore === void 0) { insertBefore = false; }
return __awaiter(this, void 0, void 0, function () {
var stylesheetHref, elId, stylesheetCode;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
if (!this.supportXLocalScheme) return [3, 1];
resourceName = this.fixLocalResourceName(resourceName);
if (path) {
this.registerLocalResource(resourceName, path);
}
stylesheetHref = this.interceptScheme + "://" + resourceName;
return [2, "window.nsWebViewBridge.injectStyleSheetFile(" + JSON.stringify(stylesheetHref) + ", " + !!insertBefore + ");"];
case 1:
elId = resourceName.replace(/^[:]*:\/\//, "").replace(/[^a-z0-9]/g, "");
return [4, fs.File.fromPath(this.resolveLocalResourceFilePath(path)).readText()];
case 2:
stylesheetCode = _a.sent();
return [2, "window.nsWebViewBridge.injectStyleSheet(" + JSON.stringify(elId) + ", " + JSON.stringify(stylesheetCode) + ", " + !!insertBefore + ")"];
}
});
});
};
WebViewExtBase.prototype.injectWebViewBridge = function () {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4, this.executeJavaScript(nativescript_webview_bridge_loader_1.webViewBridge, false)];
case 1:
_a.sent();
return [4, this.ensurePolyfills()];
case 2:
_a.sent();
return [4, this.injectViewPortMeta()];
case 3:
_a.sent();
return [2];
}
});
});
};
WebViewExtBase.prototype.injectViewPortMeta = function () {
return __awaiter(this, void 0, void 0, function () {
var scriptCode;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4, this.generateViewPortCode()];
case 1:
scriptCode = _a.sent();
if (!scriptCode) {
return [2];
}
return [4, this.executeJavaScript(scriptCode, false)];
case 2:
_a.sent();
return [2];
}
});
});
};
WebViewExtBase.prototype.generateViewPortCode = function () {
return __awaiter(this, void 0, void 0, function () {
var scriptCodeTmpl, viewPortCode;
return __generator(this, function (_a) {
if (this.viewPortSize === false) {
return [2, null];
}
scriptCodeTmpl = nativescript_webview_bridge_loader_1.metadataViewPort;
viewPortCode = JSON.stringify(this.viewPortSize || {});
return [2, scriptCodeTmpl.replace('"<%= VIEW_PORT %>"', viewPortCode)];
});
});
};
WebViewExtBase.prototype.parseWebViewJavascriptResult = function (result) {
if (result === undefined) {
return;
}
if (typeof result !== "string") {
return result;
}
try {
return JSON.parse(result);
}
catch (err) {
return result;
}
};
WebViewExtBase.prototype.writeTrace = function (message, type) {
if (type === void 0) { type = view_1.traceMessageType.info; }
if (view_1.traceEnabled()) {
view_1.traceWrite(message, "NOTA", type);
}
};
WebViewExtBase.prototype.emitToWebView = function (eventName, data) {
var scriptCode = "\n window.nsWebViewBridge && nsWebViewBridge.onNativeEvent(" + JSON.stringify(eventName) + ", " + JSON.stringify(data) + ");\n ";
this.executeJavaScript(scriptCode, false);
};
WebViewExtBase.prototype.onWebViewEvent = function (eventName, data) {
this.notify({
eventName: eventName,
object: this,
data: data,
});
};
WebViewExtBase.prototype.getTitle = function () {
throw new Error("Method not implemented.");
};
WebViewExtBase.prototype.zoomIn = function () {
throw new Error("Method not implemented.");
};
WebViewExtBase.prototype.zoomOut = function () {
throw new Error("Method not implemented.");
};
WebViewExtBase.prototype.zoomBy = function (zoomFactor) {
throw new Error("Method not implemented.");
};
WebViewExtBase.prototype.fixLocalResourceName = function (resourceName) {
if (resourceName.startsWith(this.interceptScheme)) {
return resourceName.substr(this.interceptScheme.length + 3);
}
return resourceName;
};
WebViewExtBase.prototype[view_2.isEnabledProperty.getDefault] = function () {
return true;
};
var WebViewExtBase_1;
WebViewExtBase = WebViewExtBase_1 = __decorate([
view_1.CSSType("WebView")
], WebViewExtBase);
return WebViewExtBase;
}(view_1.ContainerView));
exports.WebViewExtBase = WebViewExtBase;
exports.autoInjectJSBridgeProperty.register(WebViewExtBase);
exports.builtInZoomControlsProperty.register(WebViewExtBase);
exports.cacheModeProperty.register(WebViewExtBase);
exports.databaseStorageProperty.register(WebViewExtBase);
exports.debugModeProperty.register(WebViewExtBase);
exports.displayZoomControlsProperty.register(WebViewExtBase);
exports.domStorageProperty.register(WebViewExtBase);
exports.srcProperty.register(WebViewExtBase);
exports.supportZoomProperty.register(WebViewExtBase);
exports.scrollBounceProperty.register(WebViewExtBase);
exports.viewPortProperty.register(WebViewExtBase);
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoid2Vidmlldy1leHQtY29tbW9uLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsid2Vidmlldy1leHQtY29tbW9uLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7Ozs7O0FBRUEsbURBQXFEO0FBQ3JELHdEQUE0SjtBQUM1SiwyREFBdUU7QUFDdkUseUJBQTJCO0FBQzNCLDJGQUF1SDtBQUV2SCxxREFBZ0Q7QUFZbkMsUUFBQSwwQkFBMEIsR0FBRyxJQUFJLGVBQVEsQ0FBMEI7SUFDNUUsSUFBSSxFQUFFLG9CQUFvQjtJQUMxQixZQUFZLEVBQUUsSUFBSTtJQUNsQixjQUFjLEVBQUUsdUJBQWdCO0NBQ25DLENBQUMsQ0FBQztBQUVVLFFBQUEsMkJBQTJCLEdBQUcsSUFBSSxlQUFRLENBQTBCO0lBQzdFLElBQUksRUFBRSxxQkFBcUI7SUFDM0IsWUFBWSxFQUFFLElBQUk7SUFDbEIsY0FBYyxFQUFFLHVCQUFnQjtDQUNuQyxDQUFDLENBQUM7QUFFVSxRQUFBLGlCQUFpQixHQUFHLElBQUksZUFBUSxDQUE0QjtJQUNyRSxJQUFJLEVBQUUsV0FBVztJQUNqQixZQUFZLEVBQUUsU0FBUztDQUMxQixDQUFDLENBQUM7QUFFVSxRQUFBLHVCQUF1QixHQUFHLElBQUksZUFBUSxDQUEwQjtJQUN6RSxJQUFJLEVBQUUsaUJBQWlCO0lBQ3ZCLFlBQVksRUFBRSxLQUFLO0lBQ25CLGNBQWMsRUFBRSx1QkFBZ0I7Q0FDbkMsQ0FBQyxDQUFDO0FBRVUsUUFBQSxrQkFBa0IsR0FBRyxJQUFJLGVBQVEsQ0FBMEI7SUFDcEUsSUFBSSxFQUFFLFlBQVk7SUFDbEIsWUFBWSxFQUFFLEtBQUs7SUFDbkIsY0FBYyxFQUFFLHVCQUFnQjtDQUNuQyxDQUFDLENBQUM7QUFFVSxRQUFBLGlCQUFpQixHQUFHLElBQUksZUFBUSxDQUEwQjtJQUNuRSxJQUFJLEVBQUUsV0FBVztJQUNqQixZQUF