Meta data image for Facebook - javascript

I want to use images if I shere some links of my site. Well I am using following for it:
import { Meta, Title } from "#angular/platform-browser";
this.title.setTitle(this.data[0].title + ' - ' + this.data[0].city
);
this.meta.addTags([
{ name: 'keywords', content: 'Globetrotter, Backpacking, Hiking, Travel' + this.data[0].city + ',' + this.data[0].country},
{ name: 'description', content: this.data[0].description},
{ name: 'og:image', content: this.data[0].images[0]}
]);
Everything works fine but with image not and I am not sure if is correct. Within my index.html file I have an another image and this is occuring. Should I delete it? How can I set also the url for displaying the entire site automatically?
index.html
Facebook always shows this images even if I enter different url path.
<meta property="og:image" content="https://cdn.pixabay.com/photo/2017/09/01/21/53/blue-2705642_960_720.jpg"
/>
I want that Facebook or other sites recognise the image from here:
{ name: 'og:image', content: this.data[0].images[0]}

The problem is probably, that facebook's crawler/bot does not execute JavaScript and thus will only ever see the <meta> tag you deliver statically in your index.html.
You will either have to use a prerendering service (like prerender.io) or write the correct meta tag on the server side.

Related

How to change address bar color on mobile browsers in Gatsby.js

I would like to change address bar color for the site, which is built with Gatsby.js.
All I came up with was the modification of the "siteMetadata" section in "gatsby-config.js".
Does it make any sense?enter image description here
You can change the color on mobile Android using the meta tag theme-color in the head of your page, e.g.
<meta name="theme-color" content="#123456">
See https://stackoverflow.com/a/33193739/1247853 for a more in-detail discussion about other browsers.
If you are using the gatsby-starter-blog or the gatsby-starter-default you can set this meta tag in gatsby-config.js:
{
resolve: `gatsby-plugin-manifest`,
options: {
...
theme_color: `#123456`,
...
},
If you are not using these starters, you can use React Helmet. Install it by following the instructions on https://www.gatsbyjs.org/docs/add-page-metadata/ , then place the following code somewhere that is executed on every page, e.g. in src/components/layout.js
import { Helmet } from "react-helmet"
return (
<Helmet
meta={[
{
name: `theme-color`,
content: '#123456',
},
]}>
// ... rest of the page ...
</Helmet>
)

How Can I Pass String Variable to Anonymous Adobe View SDK Script?

I have a very basic knowledge of javascript and I have been unable to find a solution for my specific use of the Adobe View SDK API, though it seems like there should be a way. I am working on a web page to show newsletters in the pdf viewer. I have created a w3.css modal element so that I can open the viewer with a button click, and then close it with an "x" in the corner. The button click and the "x" toggle between the display style being "none" or "block". I really like this solution as it lets me use small images of the newsletters as the buttons, and it can be observed here: Test News Page by clicking on the newsletter image below May 4, 2020.
The ultimate goal I have is to be able to change the name of the pdf document that is opened in the viewer by clicking the button, which would need to pass a string variable called "docName" to the url called by the View SDK script. Since the url is already specified in the script inside my modal element when the page loads, here is the thinking I have for the additional script I need to pass my string variables: The button-click invokes my script (function changeName(docName)) and passes the "docName" variable. Then my script needs to pass this variable to the url in the View script (this is the part I don't know how to do), then refresh the page to reload my modal, and then change the display style of the modal to "block". I will copy the code for the View SDK below, showing where I need to insert the string variable with my document name:
<script src="https://documentcloud.adobe.com/view-sdk/main.js"></script>
<script type="text/javascript">
document.addEventListener("adobe_dc_view_sdk.ready", function(){
var adobeDCView = new AdobeDC.View({clientId: "06179511ab964c9284f1b0887eca1b46", divId: "adobe-dc-view"});
adobeDCView.previewFile({
content:{location: {url: "https://www.shcsfarmington.org/" + docName + ".pdf"}},
metaData:{fileName: "Newsletter_050420.pdf"}
}, {embedMode: "FULL_WINDOW", defaultViewMode: "FIT_WIDTH"});
});
</script>
It seems like this should work, but with my limited knowledge of javascript I don't know how to pass this variable to the anonymous function in the View SDK code, and I would need as much detail and specifics in the syntax of the solution. I appreciate any help with this. Thanks.
EDIT: I thought maybe it would help to show the code for the function that I have come up with so far - then it could be examined and easier to debug and comment on:
<button id="CSS-050420" onclick="changeDoc('Newsletter_050420');"></button>
<script>
function changeDoc(docName) {
/* Need to pass docName to url=https://shcsfarmington.org/2020/news/Newsletter_" + newsDate + ".pdf"; */
window.location.reload(true);
document.getElementById('viewerModal').style.display='block';
}
</script>
I created a CodePen here for you to look at.
Basically, you'll load the first file when the SDK is ready but then you need to set the adobeDCView to null before recreating it.
function showPDF(url) {
adobeDCView = null;
fetch(url)
.then((res) => res.blob())
.then((blob) => {
adobeDCView = new AdobeDC.View({
// This clientId can be used for any CodePen example
clientId: "e800d12fc12c4d60960778b2bc4370af",
// The id of the container for the PDF Viewer
divId: "adobe-dc-view"
});
adobeDCView.previewFile(
{
content: { promise: Promise.resolve(blob.arrayBuffer()) },
metaData: { fileName: url.split("/").slice(-1)[0] }
},
{
embedMode: "FULL_WINDOW",
defaultViewMode: "FIT_PAGE",
showDownloadPDF: true,
showPrintPDF: true,
showLeftHandPanel: false,
showAnnotationTools: false
}
);
});
}
The link click even will pass the url to the PDF and then display it.

Gatsby: sharing on facebook -> image is too small

I have a blog built with Gatsby and I am trying to add sharing functionality to the posts.
I know that facebook requires a certain size for the image to be added on top of the title in the sharing card, instead of on the side of the title.
When I check on the facebook debugger i see that the share card looks fine (big image on top of the title). You can check it here https://developers.facebook.com/tools/debug/og/object/?q=https%3A%2F%2Fkeen-leakey-7a99fa.netlify.com%2Ffamous-vietnamese-fruits%2F
When i try to share the post the share card is actually smaller.
I thought it could be a problem with the og:image:width and height tag not being present in the meta but after adding them they don't seem to do anything.
These are some of the properties i have in my meta
{ property: `og:url`, content: url },
{ property: `og:type`, content: `image/png` },
{ property: `og:image:width`, content: `1200` },
{ property: `og:image:height`, content: `630` },
{ property: `og:image`, content: image },
{ property: `og:title`, content: title },
{ property: `og:description`, content: metaDescription },
Any idea on what could be the problem?
The Facebook Crawler tries to follow your og:url Tag - which points to https://elingos.com - and there is no image defined - it should work when you fix the URL!
I checked it by using a Preview Plugin and then comparing that Image with the direct source!
Edit - a better Way to Debug this URLs:
Also in the Future, you can make use of the Facebook Sharing Debugger here you can see under "redirect-path" that its going to another URL :)

Print the distance result on same page without redirecting to other page during page loading

I have implemented below code to print the distance from current location and given location.
As per current situation, when the page is getting loaded then one hyperlink is being generated, when I click on that URL then it redirects to me on different page and shows the distance results.
Is there any way to print the results directly on same page on loading time without clicking on any link?
<html>
<body onLoad="javascript:showlocation()">
<p id="demo"></p>
<script>
function showlocation()
{
navigator.geolocation.getCurrentPosition(callback);
}
function callback(position)
{
var str = "Free Web Building Tutorials!";
var url = "https://maps.googleapis.com/maps/api/distancematrix/json?origins="+position.coords.latitude+","+position.coords.longitude+"&destinations=london&mode=transit&transit_mode=train&key=AIzaSyCeBdq7rr-R7w7vZCXscLWgEDb3oO9CUhw";
document.getElementById("demo").innerHTML = str.link(url);
}
</script>
</body>
</html>
You should look into how Javascript can manipulate the DOM - add and remove elements, change text and html, etc. I also recommend checking out JQuery as raw browser javascript tends to get very messy, very quickly. Highly recommended from someone who avoids libraries when possible.
You can pretty easily set the window's location in most cases with
window.location = url; // eg, 'https://google.com'
For example, if I open this with a file:// url in my browser, it works:
<script>
url = 'https://maps.googleapis.com/maps/api/distancematrix/json?origins=-93.243956,44.909974&destinations=new%20york&mode=transit&transit_mode=train&key=AIzaSyCeBdq7rr-R7w7vZCXscLWgEDb3oO9CUhw'
function setLocation(){
window.location = url;
}
</script>
<body onLoad='setLocation()' >
</body>
That should essentially have the same result of clicking a matching link. Unfortunately I couldn't get it to work in a stack overflow snippet, but I tested the content in a file locally and it redirects fine. If it doesn't work for you, I'd recommend posting a more complete example.
If you want to leave other content on the page as well, you have a few options. Some APIs allow calls from AJAX or iframes - others may use authentication, CORS, or some other means to disallow.
From the examples below, it's evident that Google is disallowing these requests by setting the appropriate headers ( The browser console will explain that display is blocked ). It's not uncommon for folks like Google to protect their free APIs with mechanisms to try to stop folks from rebranding their products or abusing their offerings. I'm sure if you look at the documentation for the API you're trying to use, it will explain how you can authenticate these requests for the user.
Below there's an example that manipulates the DOM in a few ways - with innerHTML, a vanilla javascript browser method, and with JQuery ($ is a synonym for the JQuery interface ) - which you'll see is far easier ( what you may not see is how hard it is to do things without jquery across all the relevant web browsers! ). If you swap out the URL you can see that the commands work when the URL response allows the browser to display them.
function showlocation()
{
//navigator.geolocation.getCurrentPosition(callback);
callback( { coords: { longitude: 44.909974, latitude: -93.243956 } } );
}
function callback(position)
{
var str = "Free Web Building Tutorials!";
var url = "https://maps.googleapis.com/maps/api/distancematrix/json?origins="+position.coords.latitude+","+position.coords.longitude+"&destinations=new%20york&mode=transit&transit_mode=train&key=AIzaSyCeBdq7rr-R7w7vZCXscLWgEDb3oO9CUhw";
document.getElementById("demo").innerHTML = str.link(url);
document.getElementById("iframe").src = url;
ajax(url);
}
function ajax(url){
$('#ajaxres').html("Loading...");
$.ajax({
url: url,
success: function(result, status){
$('#ajaxres').html( result );
},
error: function(req, status, msg){
$('#ajaxres').html( "Error! Status: " + status + ", message: <code>"+msg+"</code>, Response: <pre> " + JSON.stringify(req) + "</pre>" );
}
})
}
body {
background-color: aquamarine;
}
code:before {
content: "'";
}
code:after {
content: "'";
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<head>
<script>
</script>
</head>
<body onLoad="showlocation();">
<p id="demo"></p>
<p>This won't work because X-Frame-Options header of the response is SAMEORIGIN ( see browser console for errors ). You'll just see an empty box with an ugly 90s border (but ymmv):</p>
<iframe id='iframe'></iframe>
<p>The AJAX also doesn't work because </code> the Access-Control-Allow-Origin header is present on the requested resource</code> ( see console )</p>
<div id='ajaxres'></div>
</body>
</html>

Link to a page inside Sammy.js website

I am using Sammy.js for my website and I want to send a link to a page on the website to someone in an email. I have set up links like this:
this.get('#/', function(context) {
$("#main").load("sections/home.html");
});
this.get('#/:page', function(context) {
$("#main").load( "sections/" + this.params['page'] + ".html" );
});
The first one is default, so that when you type in my website, it goes to the home.html section first and if I take that out, when I go to my website, nothing loads in #main. Now, if I were to just type into my URL bar mywebsite.com/#/contact, it will load mywebsite.com/#/, in other words, straight to the home page.
I will say that if I go to the homepage first, mywebsite.com/#/, and then modify the URL to the page I want, it will work. If I hit enter to reload the page, or if I try to modify it again, it will go back to the homepage. Please help.
Try wrapping it in a document.ready and run the default route - like this:
$(document).ready(function () {
Sammy('#main', function() {
$("#header").load("templates/header.html");
$("#nav-bar").load("templates/nav-bar.html");
$("#footer").load("templates/footer.html");
this.get('#/', function(context) {
$("#main").load("sections/home.html");
});
this.get('#/:page', function(context) {
$("#main").load( "sections/" + this.params['page'] + ".html" );
});
}).run('#/');
})
That seems to work on my end.

Categories