Vue - Set different favicon when browser online or offline - javascript

I am trying to set different icons for when my browser is online(Normal logo) and offline(Greyed out logo). I am using Vue JS and I am able to detect online and offline set, I am also able to set different favicon for the different state but the offline icon won't show because my browser does not have internet to fetch the icon.
What is the best approach to achieve this? The code I am using is below, btw I am using 'v-offline' to detect online or offline states
handleConnectivityChange (status) {
status ? $('#favicon').attr('href', 'https://snackify-cdn.sfo2.digitaloceanspaces.com/favicon-on.png') : $('#favicon').attr('href', 'https://snackify-cdn.sfo2.digitaloceanspaces.com/favicon-off.png')
}

There are two elements to this, preloading the favicons, and setting them dynamically.
The first part can be achieved in various ways. I would opt for the Vue created method as you could show a spinner on the page until the component is mounted. This would probably be better suited as a mixin, instead of directly on the component.
data() {
return {
favicons: {} // we need to store the images to prevent the browser releasing them
}
},
created () {
// This can be improved but the logic is here
// Create the JS images
this.favicons = {
'online': new Image(),
'offline': new Image()
};
// Set the source properties
this.favicons.online.src = 'https://snackify-cdn.sfo2.digitaloceanspaces.com/favicon-on.png';
this.favicons.offline.src = 'https://snackify-cdn.sfo2.digitaloceanspaces.com/favicon-off.png';
}
Then, to update the favicon, you can do something along the lines of the following:
handleConnectivityChange (status) {
// Get or create the favicon
let link = document.querySelector("link[rel*='icon']") || document.createElement('link');
// Set the attributes of the favicon
link.type = 'image/x-icon';
link.rel = 'shortcut icon';
link.href = status ? this.favicons.online.src : this.favicons.offline.src;
// Append the favicon to the `head`
document.getElementsByTagName('head')[0].appendChild(link);
}
Credit to: Changing website favicon dynamically
As a side note, and this is just my opinion, I would advise dropping jQuery if you are using Vue. There is very little need for it and it just adds to the overhead. In the scenario here, you can very easily use vanilla JS to achieve what you need as the example demonstrates...

Related

Issue with using Create JS in Animate to use external assets (images/audio)

Im trying to make an interactive html ad using Adobe Animate and I do know how to do with the tools it provides while having assets stored on a local drive. But the issue is that my client wants me to export the ad as HTML and wants me to use all the assets from the web (he's providing me with all the URL links) but I have no idea how to use create js' libraries and commands so I can use those links to import the assets into the project.
I'd really appreciate if someone could help!
I asked the same question on reddit and adobe forum
Ive got one reply that was saying the following (that solution didn't work for me or maybe I didnt paste the code into Animate correctly):
to load images
if(!alreadyExecuted){
this.imageA = \[\];
var imagePaths("./images/image1", etc);
alreadyExecuted = true;
var index = 0;
imageF.bind(this)(imagePathA\[0\])
}
function loadF(){
imageF(imagePathA\[index\])
}
function imageF(imgPath) {
var image = new Image();
image.onload = onLoadF.bind(this);
image.src=imgPath;
}
function onLoadF(e) {
var img = new createjs.Bitmap(e.target);
this.imageA.push(image); // still hasn't been added to display list or positioned
index++;
if(index\<imagePathsA.length){
imageF.bind(this)(imagePathA\[index\])
} else {
// loading complete. do whatever
}
}
to load sound and play a sound:
createjs.Sound.registerSound(path to sound, "soundID");
this.your_button.addEventListener('click',playF.bind(this));
function playF(){
var soundInstance = createjs.Sound.play("soundID");
//soundInstance.addEventListener("complete",cF.bind(this)); // if you want to
know when sound completes play
}

How do I display in HTML the cover of an epub book using epub.js?

I'm using EPUB.js and Vue to render an Epub. I want to display the cover images of several epub books so users can click one to then see the whole book.
There's no documentation on how to do this, but there are several methods that indicate that this should be possible.
First off, there's Book.coverUrl() method.
Note that I'm setting an img src property equal to bookCoverSrc in the Vue template. Setting this.bookCoverSrc will automatically update the src of the img tag and cause an image to display (if the src is valid / resolves).
this.book = new Epub(this.epubUrl, {});
this.book.ready.then(() => {
this.book.coverUrl().then((url) => {
this.bookCoverSrc = url;
});
})
The above doesn't work. url is undefined.
Weirdly, there appears to be a cover property directly on book. So, I try:
this.book = new Epub(this.epubUrl, {});
this.book.ready.then(() => {
this.coverSrc = this.book.cover;
});
this.book.cover resolves to OEBPS/#public#vhost#g#gutenberg#html#files#49010#49010-h#images#cover.jpg, so at least locally when I set it to a src results in a request to http://localhost:8080/OEBPS/#public#vhost#g#gutenberg#html#files#49010#49010-h#images#cover.jpg, which 200s but returns no content. Probably a quirk of webpack-dev-server to 200 on that, but if I page through sources in Chrome dev tools I also don't see any indicate that such a URL should resolve.
So, docs not helping. I googled and found this github question from 2015. Their code is like
$("#cover").attr("src", Book.store.urlCache[Book.cover]);
Interesting, nothing in the docks about Book.store.urlCache. As expected, urlCache is undefined, though book.store exists. I don't see anything on there that can help me display a cover image though.
Using epub.js, how can I display a cover image of an Epub file? Note that simply rendering the first "page" of the Epub file (which is usually the cover image) doesn't solve my problem, as I'd like to list a couple epub files' cover images.
Note also that I believe the epub files I'm using do have cover images. The files are Aesop's Fables and Irish Wonders.
EDIT: It's possible I need to use Book.load on the url provided by book.cover first. I did so and tried to console.log it, but it's a massive blog of weirdly encoded text that looks something like:
����
So I think it's an image straight up, and I need to find a way to get that onto the Document somehow?
EDIT2: that big blobby blob is type: string, and I can't atob() or btoa() it.
EDIT3: Just fetching the url provided by this.book.cover returns my index.html, default behavior for webpack-dev-server when it doesn't know what else to do.
EDIT4: Below is the code for book.coverUrl from epub.js
key: "coverUrl",
value: function coverUrl() {
var _this9 = this;
var retrieved = this.loaded.cover.then(function (url) {
if (_this9.archived) {
// return this.archive.createUrl(this.cover);
return _this9.resources.get(_this9.cover);
} else {
return _this9.cover;
}
});
return retrieved;
}
If I use this.archive.createUrl(this.cover) instead of this.resources.get, I actually get a functional URL, that looks like blob:http://localhost:8080/9a3447b7-5cc8-4cfd-8608-d963910cb5f5. I'll try getting that out into src and see what happens.
The reason this was happening to me was because the functioning line of code in the coverUrl function was commented out in the source library epub.js, and a non-functioning line of code was written instead.
So, I had to copy down the entire library, uncomment the good code and delete the bad. Now the function works as it should.
To do so, clone down the entire epub.js project. Copy over the dependencies in that project's package.json to your own. Then, take the src, lib, and libs folders and copy them somewhere into your project. Find a way to disable eslint for the location you put these folders into because the project uses TAB characters for spacing which caused my terminal to hang due to ESLINT exploding.
npm install so you have your and epub.js dependencies in your node_modules.
Open book.js. Uncomment line 661 which looks like
return this.archive.createUrl(this.cover);
and comment out line 662 which looks like
// return this.resources.get(this.cover);
Now you can display an image by setting an img tag's src attribute to the URL returned by book.coverUrl().
this.book = new Epub(this.epubUrl, {});
this.book.ready.then(() => {
this.book.coverUrl().then((url) => {
this.bookCoverSrc = url;
});
})

Images aren't displaying on github pages

I'm using github pages to host a practice website. I've built a simple JS slideshow and the images in the slideshow are not displaying. When I use Atom live server to display the site, the images and slideshow work fine. When using github pages I inspected the active slideshow and it is moving through the image array fine as I can see the src attribute changing the way it should so I know the code is looping through the array properly. I'm not sure what is wrong.
the relevant JavaScript
const image = [
'../images/karakoy-1.jpg',
'../images/karakoy-2.jpg',
'../images/karakoy-3.jpg',
'../images/karakoy-4.jpg',
'../images/karakoy-5.jpg',
];
let i = 0;
const imageContainer = document.getElementsByClassName('slideshow-image');
const time = 3000;
function changeSlide() {
imageContainer[0].src = image[i];
if (i < image.length - 1) {
i++;
} else {
i = 0;
}
setTimeout('changeSlide()', time);
}
changeSlide();
I've also checked all the spelling and capitilization on the filenames. Everything checks out. Like I said, when I use Atom live server everything works fine.
UPDATE https://jtc10.github.io/Arcadia-Restaurant/
Here is a link to the page. Click the "reservations" link. The slideshow is on that page.
It's most likely an issue resolving relative paths between your local and live servers.
The requests with the relative paths are all returning 404 Not Found:
I prefer to use the full path from root instead. This takes the ambiguity out of the situation.
const image = [
'/images/karakoy-1.jpg',
'/images/karakoy-2.jpg',
'/images/karakoy-3.jpg',
'/images/karakoy-4.jpg',
'/images/karakoy-5.jpg',
];
It tries to load https://jtc10.github.io/images/karakoy-2.jpg which don't exist, remove the ../ from the image path.

Import image in Acrobat using JavaScript (preferred on document-level)

I am going to implement a dynamic legend using JavaScript in Adobe Acrobat.
The document contains a lot of layers. Every layer has an own legend. The origin idea is to implement the legend so, that it contains the images in a dialog box for the visible layers.
I can only hide/show the layers by setting state to false or true (this.getOCGs()[i].state = false;) on document-level.
Question 1: Can I extract data from layer somehow for legend establishing? I think no, as we only have these function on layers: getIntent(), setIntent() and setAction(). Right? Therefore I decided to arrange it so, that all needed icons for every layer are saved in a folder with corresponding names. JavaScript should import the icons and I build the a dialog window with icons of visible Layers and place a text(description for this icon).
I tried all possibilities of image import described here: http://pubhelper.blogspot.com.au/2012/07/astuces-toolbar-icons-et-javascript.html. I got only one way (Convert the icons as hexadecimal strings). This way isn't good, as it is too much work to create with an other tool a hexadecimal string from a images and place it into a javascript code.
Unfortunately, I cannot import image using other methods:(. Since the security settings in Adobe are changed after version 7 or so, it is not possible to use functions like app.newDoc, app.openDoc, even app.getPath On document-level. I decided to implement the import on a folder level using trusted functions like this:
Variant 1:
var importImg = app.trustedFunction(function() {
app.beginPriv();
var myDoc = app.newDoc({
nWidth: 20,
nHeight: 20
});
var img = myDoc.importIcon("icon", "/icon.png", 0);
app.endPriv();
return img; });
var oIcon = importImg();
The settings in Preferences->JavaScript-> JavaScript Security are disabled (Enable menu item JS execution privileges, enable global object security policy)
NotAllowedError: Security settings prevent access to this property or method.
App.newDoc:109:Folder-Level:User:acrobat.js
Variant 2:
var importImg = app.trustedFunction(function() {
var appPath = var phPath = app.getPath({
cCategory: "user",
cFolder: "javascript"
});
try {
app.beginPriv();
var doc = app.openDoc({
cPath: phPath + "/icon.png",
bHidden: true
});
app.endPriv();
} catch (e) {
console.println("Could not open icon file: " + e);
return;
}
var oIcon = util.iconStreamFromIcon(doc.getIcon("icon"));
return oIcon;});
var oIcon = importImg();
Could not open icon file: NotAllowedError: Security settings prevent access to this property or method.
At least it allows the execution of all these functions like app.newDoc, but in the second variant it says, wrong range of content or so. Maybe is here the pdf from an image created false? I just took the image and printed it into a pdf.
I tried all these possibilities with .jpg, .png, .pdf. with different sizes(big images and 20x20), It doesn't work.
Could somebody help me, as I spent a lot of time with trying different possibilities. It would be actually better to implement the main goal described above on document level, is it possible?
Thank you and kind regards,
Alex
Do you have the Console fully activated in Acrobat? If not, do so and look for error messages you get.
The first variant does not work, because myDoc is not defined (unless you have done that before you call the importImg function).
If you want to import the image into the newly created file, you will have to make a reference to the Document Object you create with newDoc(). Actually, that would make the link to myDoc, as in
var myDoc = app.newDoc(1,1)
(are you sure you want to create a document measuring 1x1 pt?)
The next issue with the first variant is a bug in Acrobat, which discards "floating" Icon Objects when saving the document; you'd have to attach the Icon Object to a field to keep it; this field can be hidden, or even on a hidden Template page in the document.

How do I Get a website's favicon using JavaScript?

I am wondering if it is possible to get a website's favicon by a URL with JavaScript.
For example, I have the URL http://www.bbc.co.uk/ and I would like to get the path to the favicon described in <link rel="icon" .../> meta tag - http://www.bbc.co.uk/favicon.ico.
I have many URLs so that should not load every page and search for link tag I think.
Any ideas?
Here are 2 working options, I tested over 100 urls and got different results which each option.
Please note, this solution is not JS, but JS may not be necessary.
<!-- Free -->
<img height="16" width="16" src='http://www.google.com/s2/favicons?domain=www.edocuments.co.uk' />
<!-- Paid -->
<img height="16" width="16" src='http://grabicon.com/edocuments.co.uk' />
Suddenly I found something called Google Shared Stuff that returns image with website's favicon by hostname:
http://www.google.com/s2/favicons?domain=www.domain.com
But fot BBC site it returns favicon a bit small. Compare:
http://www.google.com/s2/favicons?domain=www.bbc.co.uk
http://www.bbc.co.uk/favicon.ico
You could use YQL for that
http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20html%20where%20url%3D"http://bbc.co.uk/"and%20xpath%3D"/html/head/link[#rel%3D'icon']%20|%20/html/head/link[#rel%3D'ICON']%20|%20/html/head/link[#rel%3D'shortcut%20icon']%20|%20/html/head/link[#rel%3D'SHORTCUT%20ICON']"&format=json&callback=grab
This query used by Display Feed Favicons Greasemonkey script.
You can write queries in YQL console, but it requires to login (btw, using queries don't):
http://developer.yahoo.com/yql/console/#h=select%20*%20from%20html%20where%20url%3D%22http%3A//bbc.co.uk/%22and%20xpath%3D%22/html/head/link%5B#rel%3D%27icon%27%5D%20%7C%20/html/head/link%5B#rel%3D%27ICON%27%5D%20%7C%20/html/head/link%5B#rel%3D%27shortcut%20icon%27%5D%20%7C%20/html/head/link%5B#rel%3D%27SHORTCUT%20ICON%27%5D%22
It is better than http://www.google.com/s2/favicons?domain=www.domain.com
, in case favicon exists, but doesn't located in domain.com/favicon.ico
After 30.000 to 40.000 tests I noticed that you really encounter lots of different situations which have to be worked against.
The starting point is ofcourse somewhere to only look at the rel tag in there and fetch this, but along the way you will find more and more situations you will have to cover.
In case anyone will look at this thread and tries to come closer to 100% perfection I uploaded my (PHP) code here: https://plugins.svn.wordpress.org/wp-favicons/trunk/includes/server/class-http.php. This is part of a (GPL) WordPress Plugin that retrieves Favicons, more or less on request back then, out of limitations of the standard Google one (as mentioned above). The code finds a substantially amount more icons that the code of Google. But also includes google and others as image providers to shortcut further iterations on trying to retrieve the icon.
When you read through the code you will probably see some situations that you will encounter e.g. base64 data uris, pages redirecting to 404 pages or redirecting a gazillion times, retrieving weird HTTP status codes and having to check every possible HTTP return code for validness, the icons themselves that have a wrong mime type, client side refresh tags, icons in the root folder and none in the html code, etc... etc... etc...
If you go up a directory you will find other classes that then are ment to store the actual icons against their url (and ofcourse you will then need to find out which "branches" use the same favicon and which not, and find out if they belong to the same "owner" or are really different parts but under the same domain.
These days I thought that GitHub's service did a much better job than Google's:
https://favicons.githubusercontent.com/microsoft.com
Though neither are perfect it seems.
For stackoverflow:
Works: https://www.google.com/s2/favicons?domain=stackoverflow.com
Does not work: https://favicons.githubusercontent.com/stackoverflow.com
For GitHub:
Does not work: https://www.google.com/s2/favicons?domain=github.com
Works: https://favicons.githubusercontent.com/github.com
Here is an article I wrote about a solution that can fetch favicons from multiple source.
Here is the source code:
<!DOCTYPE html>
<html>
<body style="background-color:grey;">
<script type="text/javascript">
const KRequestFaviconGitHub = 'https://favicons.githubusercontent.com/';
const KRequestFaviconGoogle = 'https://www.google.com/s2/favicons?domain=';
const KDefaultUrl = KRequestFaviconGoogle;
// We rely on pre-defined hostname configurations
const hostnames = {
"stackoverflow.com": { url:KRequestFaviconGoogle+"stackoverflow.com", invert:0 },
"theregister.co.uk": { url:KRequestFaviconGoogle+"theregister.co.uk", invert:1 },
"github.com": { url:KRequestFaviconGitHub+"github.com", invert:1 },
"android.googlesource.com": { url:KRequestFaviconGoogle+"googlesource.com", invert:0 },
"developer.android.com": { url:KRequestFaviconGitHub+"developer.android.com", invert:0 }
};
document.addEventListener('DOMContentLoaded', function(event) {
addFavicon("stackoverflow.com");
addFavicon("bbc.co.uk");
addFavicon("github.com");
addFavicon("theregister.co.uk");
addFavicon("developer.android.com");
addFavicon("android-doc.github.io");
addFavicon("slions.net");
addFavicon("alternate.de");
addFavicon("amazon.de");
addFavicon("microsoft.com");
addFavicon("apple.com");
addFavicon("googlesource.com");
addFavicon("android.googlesource.com");
addFavicon("firebase.google.com");
addFavicon("play.google.com");
addFavicon("google.com");
addFavicon("team-mediaportal.com");
addFavicon("caseking.de");
addFavicon("developer.mozilla.org");
addFavicon("theguardian.com");
addFavicon("niche-beauty.com");
addFavicon("octobre-editions.com");
addFavicon("dw.com");
addFavicon("douglas.com");
addFavicon("douglas.de");
addFavicon("www.sncf.fr");
addFavicon("paris.fr");
addFavicon("bahn.de");
addFavicon("hopfully.that.domain.does.not.exists.nowaythisisavaliddomain.fart");
});
/**
*
*/
function addFavicon(aDomain)
{
var a = document.createElement("a");
a.href = "http://" + aDomain;
//a.style.display = "block";
var div = document.createElement("div");
div.innerText = aDomain;
div.style.verticalAlign = "middle";
div.style.display = "inline-block";
var img = document.createElement("img");
img.className = "link-favicon";
img.style.width = "16px";
img.style.height = "16px";
img.style.verticalAlign = "middle";
img.style.display = "inline-block";
img.style.marginRight = "4px";
a.prepend(img);
a.appendChild(div);
document.body.appendChild(a);
document.body.appendChild(document.createElement("p"));
const conf = hostnames[aDomain]
if (conf==null)
{
img.src = KDefaultUrl+aDomain;
}
else
{
img.src = conf.url;
img.style.filter = "invert(" + conf.invert + ")";
}
}
</script>
</body>
</html>

Categories

Resources