NativeScript, WebView show local HTML file if offline - webview

In NativeScript how do I show a local HTML file if the WebView is offline.
In this example I try to load a string instead of a file. But I can't get this to work ether.
let errorHtml = `
<html>
<style>
body {
background-color: red;
color: #fff;
}
</style>
<body>
<h1>Error</h1>
</body>
</html>
`;
webView.on(webViewModule.WebView.loadFinishedEvent, (args) => {
if (!args.error) {
loadLanguagesInWebView();
listenLangWebViewEvents();
} else {
webView.src = errorHtml;
}
});
webView.src = "www.google.com";

If you have included HTML files locally within your app, you don't have to worry whether the device is offline.
If you are asking about loading a remote website when device is offline, then it has nothing to do with the WebView.
It's all you have to do with your web app, implement Service Worker API. I use Angular for my web apps, all I had do was to enable the service worker module to get offline support for my web app. Depending on your web app's tech stack, you might have to do similar adjustments.

Related

I cannot access the my library when running my VodaPay Mini-Program web-view app from a browser

I am busy developing a mini-program using VodaPay mini-programs and rendering my web-page in an H5 web-view.
I have imported the CDN and it works correctly in the Simulator and while running on device on the VodaPay super-app. But when running on device I get the following error:
my is not defined
How do I prevent this from occurring? And why does this issue occur?
<script type="text/javascript" src="https://appx/web-view.min.js"></script>
<script>
// Sends message to VodaPay Mini-Program.
my.postMessage({name:"test web-view"});
// Did receive message from VodaPay Mini-Program.
my.onMessage = function(e) {
console.log(e); // {'sendToWebView': '1'}
}
</script>
The Web-View cdn will only run when your mini-app is running on device or in the Simulator. Therefore it is necessary to first check if the my. library is available in order to establish that it's running in a Mini-Program context.
<!-- MINI: Used to communicate with mini app. Have to include the script body here otherwise we get my. not recognized errors <START>-->
<script src="https://appx/web-view.min.js"></script>
<script id="messageSend">
function sendMessage(data) {
//If not in mini app webview then my. throws errors
try {
my.postMessage(data);
} catch(error) {
//Prevent my. from throwing error in browser
}
}
</script>
<script id="messageReceive">
try {
//Store message in session storage, and then change messageReceiveListener innerText to trigger a mutation event to notify that a message has arrived.
my.onMessage = function (e) {
sessionStorage.setItem('message',JSON.stringify(e));
document.getElementById('messageReceiveListener').innerText = e;
}
sessionStorage.setItem('inMiniProgram',true);
} catch(error){ //Prevent my. from throwing error in browser
sessionStorage.setItem('inMiniProgram',false);
}
</script>
<input id="messageReceiveListener" hidden></input>
<!-- MINI:<END> -->
The difficulty with wrapping all calls in try-catch is that you could be masking other errors too. What I'm doing instead is to check if the useragent contains "alipayclient" and render the html/js content conditionally, which also reduces the amount of html/js rendered for all other non-Vodapay users of the website.

Retrieve YouTube live_stats concurrent viewers from channel instead of specific live event video

I know that it is possible to get the number of concurrent viewers for a specific live streaming YouTube event with this link: https://www.youtube.com/live_stats?v={videoid}
I was wondering if is it possible to get the live_stats for a channel or playlist instead of a specific live event.
I want to embed this data in a webpage that will have multiple different live events occurring weekly. Changing the video id for each event will be a burden. If this can't be done directly, is there a way to get the video id of a current live event from a channel and use java script or php to replace the id in the link? Please help me figure this out.
After some time, I figured this out myself...
I created a PHP script that retrieves the video id of the first video in a playlist and puts the id into the live stats link. I take the link of live events and put them into a playlist for easy use.
<?php
// Retrieves video info from Youtube playlist. Just update [PLAYLIST_ID] and [API_KEY]
$json_url = "https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&maxResults=1&playlistId=[PLAYLIST_ID]&fields=items%2Fsnippet%2FresourceId%2FvideoId&key=[API_KEY]";
$json = file_get_contents($json_url);
$json=str_replace('},
]',"}
]",$json);
$data = json_decode($json, true);
$videoId = $data['items'][0]['snippet']['resourceId']['videoId'];
$viewers = file_get_contents("https://www.youtube.com/live_stats?v=$videoId");
echo $viewers;
?>
I then created an HTML page where the data is dynamically updated using jQuery.
<html>
<body>
<div id="status" style="color: #666; line-height: 24px; font-size: 19px; font-weight: normal; font: 19px Roboto,arial,sans-serif;"></div>
<script src="http://code.jquery.com/jquery-1.7.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
function update() {
$.ajax({
url: 'viewers.php',
dataType: 'text',
success: function(data) {
if (parseInt(data) == 0) {
$("#status").css({ display: "none" });
} else {
$("#status").text(parseInt(data) + ' watching now' );
}
}
})
}
update();
var statusIntervalId = window.setInterval(update, 5000);
</script>
</body>
</html>
This is how far I got. Now I am just wondering if there is a better way to combine these codes together to create less server requests. Each jQuery request happens every 5 seconds and is approximately 240 bytes is size. Even though the requests are small, they might still slow down a page.
If you can, please help me improve my solution. Thank you in advance.

YouTube API Academy

I just completed the YouTube API tutorials on Codecademy and successfully managed to display results relating to a given 'q' value in the console window provided using the following code:
// Helper function to display JavaScript value on HTML page.
function showResponse(response) {
var responseString = JSON.stringify(response, '', 2);
document.getElementById('response').innerHTML += responseString;
}
// Called automatically when JavaScript client library is loaded.
function onClientLoad() {
gapi.client.load('youtube', 'v3', onYouTubeApiLoad);
}
// Called automatically when YouTube API interface is loaded (see line 9).
function onYouTubeApiLoad() {
// This API key is intended for use only in this lesson.
// See http://goo.gl/PdPA1 to get a key for your own applications.
gapi.client.setApiKey('AIzaSyCR5In4DZaTP6IEZQ0r1JceuvluJRzQNLE');
search();
}
function search() {
// Use the JavaScript client library to create a search.list() API call.
var request = gapi.client.youtube.search.list({
part: 'snippet',
q: "Hello",
});
// Send the request to the API server,
// and invoke onSearchRepsonse() with the response.
request.execute(onSearchResponse);
}
// Called automatically with the response of the YouTube API request.
function onSearchResponse(response) {
showResponse(response);
}
and:
<!DOCTYPE html>
<html>
<head>
<script src="search.js" type="text/javascript"></script>
<script src="https://apis.google.com/js/client.js?onload=onClientLoad" type="text/javascript"></script>
</head>
<body>
<pre id="response"></pre>
</body>
</html>
The problem I am having now is that I have taken this code and put it into my own local files with the intention of furthering my understanding and manipulating it work in a way which suits me, however it just returns a blank page. I assume that it works on Codecademy because they use a particular environment and the code used perhaps only works within that environment, I am surprised they wouldn't provide information on what changes would be required to use this outside of their given environment and was hoping someone could shed some light on this? Perhaps I am altogether wrong, if so, any insight would be appreciated.
Browser Console Output:
Failed to execute 'postMessage' on 'DOMWindow': The target origin provided ('file://') does not match the recipient window's origin ('null').
I also had the same problem but it was resolved when I used Xampp. What you have to do is install xampp on your machine and then locate its directory. After You will find a folder named "htdocs". Just move your folder containing both js and HTML file into this folder. Now you have to open Xampp Control Panel and click on start button for both - Apache and SQL server. Now open your browser and type in the URL:
http://localhost/"(Your htdocs directory name containing both of your pages)"
After this, click on .html file and you are done.

How to detect if a link works?

I need to know if a link will open.
See Maximilian Hoffmann's answer for a more robust solution.
An approach like this is common - hijack the timeout to redirect to a different URL. Would this approach work for you?
<a id="applink" href="comgooglemaps://?q=Red+Lobster+Billings">Show map</a>
<script type="text/javascript">
var backup = "http://maps.google.com/?q=Red+Lobster+Billings";
function applink(fail){
return function() {
var clickedAt = +new Date;
setTimeout(function(){
if (+new Date - clickedAt < 2000){
window.location = fail;
}
}, 500);
};
}
document.getElementById("applink").onclick = applink(backup);
</script>
The solution is adding an iframe with the URL scheme to your page. It silently fails if the app is not installed, so you need to check via a timer if opening the app worked or not.
// detect iOS
if (['iPhone', 'iPad'].indexOf(navigator.platform) > -1) {
// create iframe with an Apple URL scheme
var iframe = document.createElement('iframe');
iframe.src = 'twitter://';
// hide iframe visually
iframe.width = 0;
iframe.height = 0;
iframe.frameBorder = 0;
// get timestamp before trying to open the app
var beforeSwitch = Date.now();
// schedule check if app was opened
setTimeout(function() {
// if this is called after less than 30ms
if (Date.now() - beforeSwitch < 30) {
// do something as a fallback
}
});
// add iframe to trigger opening the app
document.body.appendChild(iframe);
// directly remove it again
iframe.parentNode.removeChild(iframe);
}
I wrote a post with a more detailed example that uses this approach to open the twitter app on iOS if installed.
There isn't a way for you to know if a link will work but there is for Safari with something called Smart App Banners
<!DOCTYPE html>
<html>
<head>
<meta name="Google Maps" content="app-id=585027354"/>
</head>
<body>
The content of the document......
</body>
</html>
What it basically does is checking if an app is installed. If it's not installed the user will be directed to the app store. If it's installed the user will be able to open the app from the website with the relevant data you'd be normally passing using the url scheme.
You could use if for Google Maps.
The down side of this is that it will only work on Safari but it's still better than nothing.

Embedding NPAPI plugin in background using just Firefox Addon SDK

I have recently developed a NPAPI plugin (using FireBreath) in combination with a Google Chrome Extension. I am embedding the plugin using the background.html page and access it from multiple extension pages. Thus, the plugin remains loaded in the background page (until the extension is unloaded or the browser is closed).
I am now searching for the easiest way to port this extension to Firefox. Using the Addon SDK and it's API, i can reproduce the communication between the addon code and HTML user interface.
As there is no such global background DOM as in the Chrome Extension, how would I load the NPAPI plugin just once, without inserting it in every page of the app UI?
I've seen that using a XUL overlay would allow that - is there a way using just the addon sdk?
Edit: I've created an answer to this question with a minimal solution to this problem using page-workers.
You'll want to look at the page-worker module:
https://addons.mozilla.org/en-US/developers/docs/sdk/1.8/packages/addon-kit/page-worker.html
The caveat I would give is that the NPAPI plugin might have made assumptions about visibility or other details of the environment it is running in that simply don't apply in the page-worker environment. If you run into errors, I'd be interested to hear them!
The following code provides a minimal working solution to the problem using the page-workers as as canuckistani suggested.
Note: This solution requires the addon-sdk's unsafeWindow to access the plugin member methods. If there's a better solution that does not depend on that, feel free to send a me a note/comment.
data/background.html
<html>
<head>
<script type="text/javascript" charset="utf-8">
function pluginLoaded() {
// Create an event once plugin is loaded
// This allows the contentscript to detect plugin state
var evt = document.createEvent("CustomEvent");
evt.initCustomEvent("pluginLoaded", true, false, null);
window.dispatchEvent(evt);
}
</script>
</head>
<body>
<object id="myplugin" type="application/x-myplugin" width="0" height="0">
<param name="onload" value="pluginLoaded" />
</object>
</body>
</html>
data/background.js
var module = null;
window.addEventListener("pluginLoaded", function( event ) {
// set the module through unsafeWindow
module = unsafeWindow.document.getElementById("myplugin");
module = XPCNativeWrapper.unwrap(module);
self.port.emit("pluginLoaded");
});
// Handle incoming requests to the plugin
self.port.on("pluginCall", function(msg) {
var response;
if (module) {
// Call NPAPI-plugin member method
response = module[msg.method].apply(this, msg.args);
} else {
response = {error: true, error_msg: "Module not loaded!"};
}
self.port.emit("pluginResponse", {data: response});
});
main.js
// Create background page that loads NPAPI plugin
var plugin = require("page-worker").Page({
contentURL: data.url("background.html"),
contentScriptFile: data.url("background.js"),
contentScriptWhen: "ready"
});
// Send request to plugin
plugin.port.emit("pluginCall", message);

Resources