I have a Google Doc with images. I would like to open a selected image in a page in another window (the google doc is a role playing game scenario and I want to show the image to my players on a second screen).
I have created a sidebar with a google script and I am able to show the selected image in this sidebar.
Now, I don't know how to open a new window (or connect a existing window) and send the image data to this window.
I start by trying to use the "PresentationRequest", but I have the error "PresentationRequest is not defined" on the init...
presentationRequest = new PresentationRequest('receiver.html');
My source :
https://developers.google.com/web/updates/2018/04/present-web-pages-to-secondary-attached-displays
For information (and if it helps someone) how I send the image to the sidebar page:
var doc = DocumentApp.getActiveDocument();
var selection = doc.getSelection();
if (selection) {
var elements = selection.getRangeElements();
var e = elements[0].getElement();
if (e.getType() == DocumentApp.ElementType.INLINE_IMAGE) {
var blobImg = e.asInlineImage().getBlob();
return 'data:' + blobImg.getContentType() + ';base64,' + Utilities.base64Encode(blobImg.getBytes());
}
}
The HTML code :
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<style type="text/css">
.tailMax {
max-width: 260px;
max-height: 260px;
}
.centre {
display: block;
margin-left: auto;
margin-right: auto;
}
</style>
</head>
<body>
<form id="formJdr">
<div style="padding-bottom: 10px;">
<button type="button" id="btnAffImg" onclick="google.script.run.withSuccessHandler(afficheImg).selectImg()">Afficher</button>
<label id="lblImg">Sélectionnez une image</label>
</div>
<img id="img" class="tailMax centre"/>
</form>
<script>
function afficheImg(valeur) {
if (typeof value === "string"){
// Message
afficheMessage(valeur);
}
else {
try {
// Image to show
afficheMessage("");
document.getElementById("img").src = valeur;
}
catch(error) {
afficheMessage(error);
}
}
}
function afficheMessage(message) {
document.getElementById("lblImg").innerHTML = message;
}
</script>
</body>
</html>
I use a Chrome browser.
Do you think it is possible?
Modify your try statement as following:
try {
// Image to show
afficheMessage("");
var image=document.getElementById("img");
image.src = valeur;
var w = window.open("", '_blank');
w.document.write(image.outerHTML);
}
var w = window.open("", '_blank'); w.document.write(image.outerHTML); allows you to open a new window and then write the image as bytearray into it.
Ok, with the help of Ziganotschka, I update my javascript code for this.
Now I can change the image in the new window.
Just some improvements to make on the opening of this window and it will be good.
<script>
var affichage;
function afficheImg(valeur) {
if (typeof value === "string"){
afficheMessage(valeur);
}
else {
try {
afficheMessage("");
var image = document.getElementById("img");
image.src = valeur;
affichage.document.body.innerHTML = "";
affichage.document.write(image.outerHTML);
}
catch(error) {
afficheMessage(error);
}
}
}
function afficheMessage(message) {
document.getElementById("lblImg").innerHTML = message;
}
window.onload = function() {
affichage = window.open("", '_blank');
</script>
Related
I want to create an image in javascript and then get its dimensions from a function.
I always get 0 0 or undefined undefinde
let rocketimage=document.createElement('img');
rocketimage.src='rocket.png';
rocketimage.id='rocketimage';
const body=document.getElementsByTagName('body')[0];
body.appendChild(rocketimage);
function getDimensions(id) {
var element = document.getElementById(id);
if (element && element.tagName.toLowerCase() == 'img') {
return {
width: element.width,
height: element.height
};
}
}
// using the function on the above image:
var dims = getDimensions('rocketimage');
console.log(dims.width);
console.log(dims.height);
<!DOCTYPE html>
<html lang="de" dir="ltr">
<head>
<meta charset="utf-8">
<title>rocktetgame</title>
</head>
<body>
<script src="getimagesize.js" charset="utf-8"></script>
</body>
</html>
You see, the function getDimensions() was called before an image got fully-loaded.
We use window.onload = function(){} or other alternatives like Jquery Ready Function to solve these type of issues.
I also removed const body=document.getElementsByTagName('body')[0]; because in this case we can just call it with document and it requires less code, which makes the script look cleaner.
<script>
function getDimensions(id) {
var element = document.getElementById(id);
if (element && element.tagName.toLowerCase() == 'img') {
return {
width: element.width,
height: element.height
};
}
}
let rocketimage = new Image();
rocketimage.src ='rocketimage';
rocketimage.id ='rocketimage';
document.body.appendChild(rocketimage);
window.onload = function() {
dimentions = getDimensions('rocketimage');
console.log(dimentions);
}
</script>
You need to give the browser time to load the image.
Images have an onload callback that you can hook yourself up to.
As soon as it fires, it is safe to use the width and height properties.
Try this one with setAttribute, worked for me.
I took an image from the internet for the example.
let rocketimage=document.createElement('img');
rocketimage.setAttribute("src", "https://r-
cf.bstatic.com/images/hotel/max1024x768/186/186280585.jpg");
rocketimage.setAttribute('id','rocketimage')
const body=document.getElementsByTagName('body')[0];
body.appendChild(rocketimage);
function getDimensions(id) {
var element = document.getElementById(id);
if (element || element.tagName.toLowerCase() == 'img') {
return {
width: element.width,
height: element.height
};
}
}
// using the function on the above image:
var dims = getDimensions('rocketimage');
console.log(dims.width);
console.log(dims.height);
You need to wait till onload event to get actual height and width. Something like this will work.
const rocketimage = document.createElement('img');
// OR - const rocketimage = new Image();
rocketimage.src = 'https://images.freeimages.com/images/large-previews/e2a/boise-downtown-1387405.jpg';
rocketimage.onload = function () {
console.log('Height :', this.height);
console.log('Width :', this.width);
};
This question already has answers here:
How do I check if file exists in jQuery or pure JavaScript?
(19 answers)
Closed 3 years ago.
We are currently developing a web interface (only for viewing) for one of our applications, which is C++ based. The web application uses Bootstrap. I am a JavaScript and JQuery beginner.
At the top of the web page I need to display a thumbnail if it's available, otherwise a default picture.
I have the link to the thumbnail, even if it's not pointing at any resources (the picture can be deleted for different reasons that are irrelevant here, and this is not an error). The link to the thumbnail has the following format /resources/id={some_id}
Using jquery, I do the following :
<html>
<body>
<img id="thumbnail" />
<script>
var jobId = getUrlVars()["jobId"];
$.getJSON("/jobs?jobId=" + jobId, function(jobDescription) {
/* thumbnailSrc will always contain something valid,
but that can point to some not existing picture */
let thumbnailSrc = jobDescription.thumbnailSrc;
$('#thumbnail').attr("src", thumbnailSrc);
});
</script>
</body>
</html>
If the link is valid, everything is fine; otherwise, it displays a broken picture. I would like to test if thumbnailSrc is a valid link (not returning a 404 error) to be able to do something like:
<script>
var jobId = getUrlVars()["jobId"];
$.getJSON("/jobs?jobId=" + jobId, function(jobDescription) {
let thumbnailSrc = jobDescription.thumbnailSrc;
if (/* thumbnailSrc link is working */)
$('#thumbnail').attr("src", thumbnailSrc);
else
$('#thumbnail').attr("src", "/resources/default_picture.png");
});
</script>
How can I test in Javascript (or JQuery) if a link is valid?
Use a callback function like below
<img src="image.gif" onerror="myFunction()">
<script>
function myFunction() {
alert('The image could not be loaded.');
}
</script>
You can assign to your image an onerror event, and inside it you can assign to src the fallback source, e.g. in jQuery it would be like this:
$(function() {
$('#thumbnail').on('error', function() {
let fallback_img_src = 'https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png';
$(this).attr('src', fallback_img_src);
});
let wrong_img_src = 'wrong_img_src.jpg';
$('#thumbnail').attr('src', wrong_img_src);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img id="thumbnail" />
The following loads the image and if 404, loads the default:
let src = "https://lh3.googleusercontent.com/PS1VZpazvgLZx9GkeudW7vn4JAMp42SpLcV3ugn45z5HFdnx5iXxENLdjN3ZhaYhAa3aByKe9HJAT_b-0LIJeeJGL2-_vS7RxLKQv6kEAA";
let srcBad = "https://lh3.googleusercontent.com/not_exist";
let srcDefault = "https://storage.googleapis.com/gd-wagtail-prod-assets/images/evolving_google_identity_2x.max-4000x2000.jpegquality-90.jpg";
let elImg = document.createElement("img");
let elImg2 = document.createElement("img");
function loadImage(el, src, srcDefault) {
el.addEventListener("load", function(ev) {
document.body.appendChild(el);
});
el.addEventListener("error", function(ev) {
console.log("load error, using default");
el.src = srcDefault;
});
el.src = src;
}
loadImage(elImg, src, srcDefault);
loadImage(elImg2, srcBad, srcDefault);
img {
width: 200px
}
In jQuery:
let src = "https://lh3.googleusercontent.com/PS1VZpazvgLZx9GkeudW7vn4JAMp42SpLcV3ugn45z5HFdnx5iXxENLdjN3ZhaYhAa3aByKe9HJAT_b-0LIJeeJGL2-_vS7RxLKQv6kEAA";
let srcBad = "https://lh3.googleusercontent.com/not_exist";
let srcDefault = "https://storage.googleapis.com/gd-wagtail-prod-assets/images/evolving_google_identity_2x.max-4000x2000.jpegquality-90.jpg";
let elImg = document.createElement("img");
let elImg2 = document.createElement("img");
function loadImage(el, src, srcDefault) {
$(el).on("load", function(ev) {
document.body.appendChild(el);
});
$(el).on("error", function(ev) {
console.log("load error, using default");
el.src = srcDefault;
});
el.src = src;
}
loadImage(elImg, src, srcDefault);
loadImage(elImg2, srcBad, srcDefault);
img {
width: 200px
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
I have a series of expandable drop-down tabs using the ToggleList javascript function below. When the tab is closed I would like to display expand.png and when it's open I would like to display close.png. Right now Any help would be appreciated.
The code below expands\minimizes the dropdown tabs, but is not switching the png files.
Full javascript + html:
<script type="text/javascript">
function ToggleList(IDS) {
HideRange('ulist','div',IDS); // not required unless using 'HideRange()' below
var CState = document.getElementById(IDS);
if (CState.style.display != "block") { CState.style.display = "block"; }
else { CState.style.display = "none"; }
// get a reference to the image contained in the <a> that was just clicked
var img = this.getElementsByTagName('img')[0];
// switch the graphic, if it's expand set it to collapse, otherwise expand
img.src = img.src == "expand.png" ? "minimize.png" : "expand.png";
}
function HideRange(sect,elTag,IDS) {
var ContentObj = document.getElementById(sect);
var AllContentDivs = ContentObj.getElementsByTagName(elTag);
}
</script>
<ul id="ulist">
<li><p><img src="expand.png"/> Subject</p></li>
<div id="expand0" class="divInfo">Text</div>
<li><p><img src="expand.png"/> Subject</p></li>
<div id="expand1" class="divInfo">Text</div>
<li><p><img src="expand.png"/> Subject</p></li>
<div id="expand3" class="divInfo">Text</div>
</ul>
Here's a simple way to implement that - comments in the code
function ToggleList(IDS) {
HideRange('ulist','div',IDS); // not required unless using 'HideRange()' below
var CState = document.getElementById(IDS);
if (CState.style.display != "block") { CState.style.display = "block"; }
else { CState.style.display = "none"; }
// get a reference to the image contained in the <a> that was just clicked
var img = this.getElementsByTagName('img')[0];
// switch the graphic, if it's expand set it to collapse, otherwise expand
img.src = img.src == "img/expand.png" ? "img/collapse.png" : "img/expand.png";
}
I am using javascript to periodically replace a .png picture, which ist viewed fullscreen as the only content of a site. No matter how I try, in Firefox, after being loaded (as seen via firebug), the new image is always drawn from top to bottom. This takes some seconds. Is there any way to prevent this and show the picture all at once?
This is my current javascript code:
function preloadScreenshotPeriodically(){
var new_screenshot = new Image();
new_screenshot.src = "screenshot.png?defeat_firefox_caching=" + counter;
new_screenshot.id = "screenshot";
counter = counter + 1;
new_screenshot.onload = function(){
loadScreenshot(new_screenshot);
setTimeout("preloadScreenshotPeriodically();", 5000);
};
}
function loadScreenshot(new_screenshot){
document.getElementById("screenshot").parentNode.replaceChild(new_screenshot, document.screenshot);
}
I also tried to use two images, one of them hidden. Then loading the picture in the hidden one and swapping them. Same results :/
In an other version, I fetched the image with Ajax and after loading is complete, changed the url of the img-tag. My hope was, that the browser would recognize the picture had already been loaded and fetch it from the browsercache rather than loading it. But this didn't happen and I ended up with two requests to the server for one picture and the same slow drawing of it as in my other trys.
edit:
Now I tried it like suggested in answer 1. While it works just fine if I switch the picture when I load the next one (I don't want this), trying to switch it as soon as it is loaded (what I want) results in a blank window (very short) and visible loading of the picture as described above.
this works:
<body>
<style type="text/css">
#loaderWin { display:block; height:1px; width:1px; overflow:hidden; }
</style>
<div id="imagewin"></div>
<div id="loaderWin"></div>
<script type="text/javascript">
var screenshotCount=0;
function showFirstImage() {
loadNextImage();
}
function showNewImage() {
loadNextImage();
}
function nextImageLoaded() {
// swapImage();
}
function loadNextImage() {
swapImage();
screenshotCount = screenshotCount +1;
var nextImage = "<img id='loaderWinImg' src='screenshot.png?x="+screenshotCount+"' onload='nextImageLoaded()' />";
document.getElementById('loaderWin').innerHTML = nextImage;
}
function swapImage() {
document.getElementById("loaderWinImg").onload = '';
var newimage=document.getElementById('loaderWin').innerHTML;
document.getElementById('imagewin').innerHTML = newimage;
}
var showImages = setInterval("showNewImage()",15000);
showFirstImage();
</script>
</div>
</body>
</html>
this doesn't work:
<body>
<style type="text/css">
#loaderWin { display:block; height:1px; width:1px; overflow:hidden; }
</style>
<div id="imagewin"></div>
<div id="loaderWin"></div>
<script type="text/javascript">
var screenshotCount=0;
function showFirstImage() {
loadNextImage();
}
function showNewImage() {
loadNextImage();
}
function nextImageLoaded() {
swapImage();
}
function loadNextImage() {
screenshotCount = screenshotCount +1;
var nextImage = "<img id='loaderWinImg' src='screenshot.png?x="+screenshotCount+"' onload='nextImageLoaded()' />";
document.getElementById('loaderWin').innerHTML = nextImage;
}
function swapImage() {
// loadNextImage();
document.getElementById("loaderWinImg").onload = '';
var newimage=document.getElementById('loaderWin').innerHTML;
document.getElementById('imagewin').innerHTML = newimage;
}
var showImages = setInterval("showNewImage()",15000);
showFirstImage();
</script>
</div>
</body>
</html>
The problem can be seen here (in firefox problem like described above, in chrome there are no pauses between pictureloads and there is a blank window in between picture changes): http://sabine-schneider.silbe.org:1666/test.html
And here, what Rob suggested in answer 1 without any changes (displays the picture fine in firefox, but not in chrome - there I get a blank window in between picture changes): http://sabine-schneider.silbe.org:1666/test0.html
sounds like the image is "progressive" ( interlaced) and the preload needs more time for it to complete download.
You can set a width and height to the image also for a more stable presentation
( poss )
using
?defeat_firefox_caching=" + counter;
means you never cache the image ( which has confused me about your question ) - remove that line( unless you need it for something you haven't mentioned)
update: Can you try ...
<style type="text/css">
#loaderWin { display:block; height:1px; width:1px; overflow:hidden; }
</style>
<div id="imagewin"></div>
<div id="loaderWin"></div>
<script type="text/javascript">
var screenshotCount=0;
function showNewImage() {
screenshotCount = screenshotCount +1;
var newimage=document.getElementById('loaderWin').innerHTML;
document.getElementById('imagewin').innerHTML = newimage;
var nextImage = "<img src='screenshot.png?defeat_firefox_caching="+screenshotCoun+"'/>";
document.getElementById('loaderWin').innerHTML = nextImage;
}
var showImages = setInterval("showNewImage()",5000);
</script>
So I'm trying to complete some javascript and having trouble codeing links to update a image. In a parent window using my script I open a remote child window to operate the image. THe links on the child window open the first image and last image. Two more links control the "next" image and previous image.
Heres what I have so far
HTML PARENT WINDOW : (haven't figured out how to post html on here btw :( )
<html>
<head>
<title> </title>
<script type="text/javascript" src="scriptss.js">
</script>
</head>
<body>
<img src="images/img0.jpg" width="200px" height="200px" id="myImage" name="myImage" /></img>
<h1>XXX</h1>
<a href="#" id = "opens" >open</a>
</br>
close
</br>
</body>
<html>
Child Window HTML:
<html>
<head>
<title> Matt Beckley Assignment Remote</title>
<link rel="stylesheet" type="text/css" href="remote.css" />
<script type="text/javascript" src="scriptss.js">
</script>
</head>
<body>
<h1>My Remote</h1>
First Image
</br>
Next Image
</br>
Previous Image
</br>
Last Image
</br>
close
</body>
</html>
JAVASCRIPT child node
var newWindow = null;
window.onload = init;
var myImages = new Array();
//start loop - length depends on how many images you need to preload
for (var i=0; i<5; i++) {
//create new image object
var tempImage = new Image();
//assign name|path of image to src property of image object
tempImage.src = "img" + (i+1) + ".jpg";
}
function init()
{
for(var i=0; i<document.links.length; i++)
{
document.links[i].onclick = changeWindowState;
}
}
function windowOpen(){
if(newWindow && !newWindow.closed){
return true;
}
return false;
}
function changeWindowState()
{
if (this.id =="closes")
{
if(windowOpen())
{
newWindow.close();
}
else
{
alert("The window isn't open");
}
}
if (this.id =="closess")
{
if(windowOpen())
{
remotetest.html.close();
}
else
{
alert("The window isn't open");
}
}
if(this.id == "opens")
{
if(windowOpen())
{
alert("The Window is alreadyopen!");
}
else
{
newWindow = window.open ("remotetest.html","remoteWin","resizeable=no,width=200,height=200");
}
}
return false;
}
function first()
{
if(this.id == "first")
{
alert("box");
}
else(this.id == "first")
{
alert("box");
}
}
Anyways I'm preloading my images and I got that figured out correctly. I'm trying to access my element in the parent node in the image tag and display an array element 1-6. In other words image 1 thru image 6
THe idea is to press a button in the child node and display the first image element[0] for instand press another button element[5]
or press another button for next element[i+1] with an another button. THanks for the help.
There are quite some ways on how to communicate between parent and child window. See this for more info.