Getting the Window Height of an Embedded Tableau Dashboard - javascript

After my dashboard initializes and is fully loaded, I need to get the window height of the embed inside the iframe. Ideally, I'd like to get innerHeight inside of onFirstInteractive, but am unable to do so.
function initViz() {
var containerDiv = document.getElementById("vizContainer");
var url = "http://public.tableau.com/views/RegionalSampleWorkbook/Storms";
var options = {
onFirstInteractive: function() {
// How do I get the height of the rendered contents?
}
};
var viz = new tableau.Viz(containerDiv, url, options);
}

Subscribe to the VIZ_RESIZE event, it provides the new dimensions of the iframe on initialization and resize:
viz.addEventListener(tableau.TableauEventName.VIZ_RESIZE, function(event) {
console.log(event.getAvailableSize());
});
Which gives the following:
When the iframe appears like this:
If you absolutely want to retrieve the information in onFirstInteractive, you can do this:
onFirstInteractive: function(viz) {
const iframeStyle = viz.$1._impl.$1h.style;
const { height, width } = iframeStyle;
console.log({ height, width });
}
But it's a little bit hacky because this solution uses properties that are not supposed to be public, so this kind of code may break on future Tableau JS library updates.

Related

Can I "freeze" fixed elements to take a screenshot with getDisplayMedia?

I'm implementing a chrome extension with javascript to take a screenshot of a full page, so far I've managed to take the screenshot and make it into a canvas in a new tab, it shows the content of a tweet perfectly, but as you can see, the sidebars repeat all the time (Ignore the red button, that's part of my extension and I know how to delete it from the screenshots) screenshot of a tweet
This is the code I'm using to take the screenshot:
async function capture(){
navigator.mediaDevices.getDisplayMedia({preferCurrentTab:true}).then(mediaStream=>{
scrollTo(0,0);
var defaultOverflow = document.body.style.overflow;
//document.body.style.overflow = 'hidden';
var totalHeight = document.body.scrollHeight;
var actualHeight = document.documentElement.clientHeight;
var leftHeight = totalHeight-actualHeight;
var scroll = 200;
var blob = new Blob([document.documentElement.innerHTML],{ type: "text/plain;charset=utf-8" });
console.log('total Height:'+totalHeight+'client height:'+actualHeight+'Left Height:'+leftHeight);
var numScreenshots = Math.ceil(leftHeight/scroll);
var arrayImg = new Array();
var i = 0;
function myLoop() {
setTimeout(function() {
var track = mediaStream.getVideoTracks()[0];
let imgCapture = new ImageCapture(track);
imgCapture.grabFrame().then(bitmap=>{
arrayImg[i] = bitmap;
window.scrollBy(0,scroll);
console.log(i);
i++;
});
if (i <= numScreenshots) {
myLoop();
}else{
document.body.style.overflow = defaultOverflow;
saveAs(blob, "static.txt");
printBitMaps(arrayImg, numScreenshots, totalHeight);
}
}, 250)
}
myLoop();
})
}
async function printBitMaps(arrayImg, numScreenshots, totalHeight){
var win = window.open('about:blank', '_blank');
win.document.write('<canvas id="myCanvas" width="'+arrayImg[0].width+'px" height="'+totalHeight+'px" style="border:5px solid #000000;"></canvas>');
var e = numScreenshots+1;
function printToCanvas(){
setTimeout(function(){
var canvas = win.document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
ctx.drawImage(arrayImg[e], 0, 200*e);
e--;
if(e>=0){
printToCanvas();
}
},10);
}
printToCanvas();
}
Do you know any way by CSS or javascript that I can use to make the sidebars stay at the top of the page so they don't keep coming down with the scroll?
It's not really a case of "the sidebars ... coming down with the scroll" - the code you're using is taking a first screenshot, scrolling the page, taking another screenshot and then stitching it onto the last one and iterating to the bottom of the page. Thus it's inevitable you're seeing what you see on the screen at the point you take the subsequent screenshots.
To resolve your issue, after your first screenshot you would need to set the div element for the side bar to be display=None by use of CSS. You can find details of the side bar by using the browser Dev Tools, right clicking an using "Inspect" in Chrome.
From what I can see, Twitter seems to use fairly cryptic class names, so it might be easiest and more robust to identify the div for the side bar with some other attribute. It appears they set data-testid="sidebarColumn" on it so give using that a go (but YMMV).

Pan-zoom a PDF (Javascript)

I'm trying to pan-zoom with the mouse a <div> that contains a PDF document.
I'm using PDF.js and panzoom libraries (but other working alternatives are welcome)
The snippet below basically does this task, but unfortunately, after the <div> is panzoomed, the PDF is not re-rendered, then its image gets blurry (pan the PDF with the mouse and zoom it with the mouse-wheel):
HTML
<script src="https://mozilla.github.io/pdf.js/build/pdf.js"></script>
<script src="https://cdn.jsdelivr.net/npm/#panzoom/panzoom#4.3.2/dist/panzoom.min.js"></script>
<div id="panzoom-container">
<canvas id="the-canvas"></canvas>
</div>
<style>
#the-canvas {
border: 1px solid black;
direction: ltr;
}
</style>
JAVASCRIPT
// Loaded via <script> tag, create shortcut to access PDF.js exports.
var pdfjsLib = window['pdfjs-dist/build/pdf'];
// The workerSrc property shall be specified.
pdfjsLib.GlobalWorkerOptions.workerSrc = 'https://mozilla.github.io/pdf.js/build/pdf.worker.js';
var pdfDoc = null,
canvas = document.getElementById('the-canvas'),
ctx = canvas.getContext('2d');
var container = document.getElementById("panzoom-container")
function renderPage(desiredHeight) {
pdfDoc.getPage(1).then(function(page) {
var viewport = page.getViewport({ scale: 1, });
var scale = desiredHeight / viewport.height;
var scaledViewport = page.getViewport({ scale: scale, });
canvas.height = scaledViewport.height;
canvas.width = scaledViewport.width;
// Render PDF page into canvas context
var renderContext = {
canvasContext: ctx,
viewport: scaledViewport
};
page.render(renderContext);
});
}
// Get the PDF
var url = 'https://raw.githubusercontent.com/mozilla/pdf.js/ba2edeae/web/compressed.tracemonkey-pldi-09.pdf';
pdfjsLib.getDocument(url).promise.then(function(pdfDoc_) {
pdfDoc = pdfDoc_;
// Initial/first page rendering
renderPage(250);
});
var panzoom = Panzoom(container, {
setTransform: (container, { scale, x, y }) => {
// here I can re-render the page, but I don't know how
// renderPage(container.getBoundingClientRect().height);
panzoom.setStyle('transform', `scale(${scale}) translate(${x}px, ${y}px)`)
}
})
container.addEventListener('wheel', zoomWithWheel)
function zoomWithWheel(event) {
panzoom.zoomWithWheel(event)
}
https://jsfiddle.net/9rkh7o0e/5/
I think that the procedure is correct, but unfortunately I'm stuck into two issues that must be fixed (then I ask for your help):
I don't know how to re-render correctly the PDF after the panzoom happened.
consecutive renderings have to be queued in order to make this work properly (so that the PDF doesn't blink when panzooming)
How could I fix 1 and 2 ? I could not find any tool for doing that on a PDF, apart the panzoom lib.
Thanks
After some days of attempts, I solved the problem.
The tricky part was to scale down the contained canvas after the container has been scaled, with a transform-origin CSS attribute set:
canvas.style.transform = "scale("+1/panzoom.getScale()+")"
Here is a fiddle of a PDF that can pan-zoomed. Each new render is done after a small delay (here it is set to 250ms) which corresponds to a sort of "wheel stop event".
function zoomWithWheel(event) {
panzoom.zoomWithWheel(event)
clearTimeout(wheelTimeoutHandler);
wheelTimeoutHandler = setTimeout(function() {
canvas.style.transform = "scale("+1/panzoom.getScale()+")"
if (pdfDoc)
renderPage(panzoom.getScale());
}, wheelTimeout)
}
https://jsfiddle.net/7tmk0z42/

Get offsetHeight after manipulating DOM

I wrote the following code:
var image_pinch_help = document.getElementById("image_pinch_help");
var pinch_img_el = document.getElementById("pinch_img_el");
function openImage(img_url) {
pinch_img_el.src = img_url;
if (pinch_img_el.complete) {
IMGloaded();
}
else {
pinch_img_el.addEventListener('load', IMGloaded())
pinch_img_el.addEventListener('error', function() {
alert('error')
});
}
image_pinch_help.style.display = "block";
document.getElementById("pinch_values").setAttribute("content", "");
}
function IMGloaded() {
var screen_height = window.screen.height;
console.log("HERE IS THE HEIGHT: " + screen_height);
var img_height = pinch_img_el.offsetHeight;
console.log("HERE IS THE IMAGE: " + img_height);
}
The code starts at the function openImage(). This function is called to open an Image at my webpage. So the image gets the full width of the screen. The screen where the image is shown on is image_pinch_help. You see that I make this screen visible. To allow the user to zoom into the image I am manipulation the HTML DOM, that the user can scroll at the whole page. I do this here: document.getElementById("pinch_values").setAttribute("content", "");.
When the Image loaded I need to get the height of the screen, which works perfectly. But I also need to get the height of the loaded image. The problem is that its always returning an empty string. I read a long time ago that this could be caused by HTML DOM Manipulations.
But how to fix this disaster?
~Marcus

How to communicate between two views( different js files) in Famo.us

I am creating a famo.us app in which header footer and content area is there. In content area different views are rendering using RenderController on action of each other and in each view different sub views are there. Events are communicating through java script using document.dispatchEvent() and addEventLiserner() method instead of famo.us events. I just want to ask that whether it is worth using this listener functions.
As I have tried through famous events like setInputHandler, setOnputHandler, emit , addListener, pipe given in famo.us documentation, But I cannot able to communicate using this.
The main question is the static app created by me is taking huge time when loaded from server and animations are running very slowly. Is there any solution for this.
Actually code is too long dummy example is below. I am creating an application having header footer and content view. In Content view I am rendering different views using renderController.
Content View
define(function(require, exports, module) {
var View = require('famous/core/View');
var Surface = require('famous/core/Surface');
var LoginView = require('views/login/LoginView');
var AccountsView = require('views/login/AccountsView'); //need to call on login
function ContentView() {
View.apply(this, arguments);
var renderController = new RenderController({
inTransition: {curve: Easing.easeOut, duration: 1000},
outTransition: {curve: Easing.easeIn, duration: 1000},
overlap: true,
});
var loginview = new LoginView();
renderController.show(loginview); //rendered initially
this.add(renderController);
document.addEventListener("showAccountsView",function(){
var accoutsView = new AccountsView()
renderController.show(accoutsView);
}.bind(this));
}
});
Login View
define(function(require, exports, module) {
var View = require('famous/core/View');
var Surface = require('famous/core/Surface');
var InputSurface = require("famous/surfaces/InputSurface");
function LoginView() {
View.apply(this, arguments);
var loginBoxContainer = new ContainerSurface({
classes:["backfaceVisibility"],
size:[undefined,295],
properties: {
overflow: 'hidden',
padding:'0 10px'
}
});
this.add(loginBoxContainer);
var userInput = new InputSurface({
size: [undefined, 45],
});
var userInputModifier = new StateModifier({
transform: Transform.translate(0,53,1)
});
var pwdInput = new InputSurface({
classes:["pwdInput"],
size: [undefined, 45],
});
var pwdInputModifier = new StateModifier({
transform: Transform.translate(0,100,1)
});
loginBoxContainer.add(userInputModifier).add(userInput);
loginBoxContainer.add(pwdInputModifier).add(pwdInput);
var submit = new Surface({
content:["Submit"],
size:[100,30],
});
submit.on("click",function(){
document.dispatchEvent(new Event("showAccountsView"));
});
loginBoxContainer.add(submit);
}
});
I have to render different view on clicking ligin submit button. I have used dispatchEvent and addEventListener of Javascript to make communication between two files. I want to use famous events. I have tried various ways using setInputHandler, setOnputHandler, emit , addListener, pipebut could not able to do that as data and listener functions cannot calling. Please explain..
Inside LoginView, replace this code:
submit.on("click",function(){
document.dispatchEvent(new Event("showAccountsView"));
});
with:
submit.on("click",function(){
this._eventOutput.emit('showAccountsView', { data: someValue });
});
In ContentView, replace:
document.addEventListener("showAccountsView",function(){
var accoutsView = new AccountsView()
renderController.show(accoutsView);
}.bind(this));
with:
loginView.on('showAccountsView', function(data){
var accoutsView = new AccountsView()
renderController.show(accoutsView);
}.bind(this));

loading cached fonts at the right time

I have some webfonts that get loaded via Webfontloader load like this ...
<script src="//ajax.googleapis.com/ajax/libs/webfont/1.5.10/webfont.js"></script>
<script>
WebFont.load({
custom: {
families: ['BlenderProBook', 'BlenderProMedium']
}
});
</script>
And it works great when first loading the page ... Problems is, when refreshing the page it only retrieves the cached fonts when requested in html and not before my ReactJS app runs (when the Webfontloader normally gets them). This is too late for me, because I'm using them in pre-generated SVG.
Is there a way to force it to get the uncached fonts each time? Or better, load the cached fonts at the correct time.
I found a solution to this, which I will take as my answer if no-one else can supply a better one.
My font is being used extensively in the app to calculate text widths and therefore layout ... (which is why it needs to be loaded before the app runs), so I decided to use the text width code as a test to block the app from running.
Here's the code
var testFont = require('./components/svgText.js');
var timer = setInterval(function () {
var test = (testFont('TEST', 'BlenderProBook', 20).width === 39.75);
if (test) {
clearInterval(timer);
Router.run(routes, function (Handler) {
React.render(<Handler/>, document.body);
});
}
}, 50);
where svgTest.js uses Raphael SVG to generate SVG text and retrieve the measurements like this:-
renderedTextSize = function (string, font, fontSize) {
var paper = Raphael(0, 0, 0, 0);
paper.canvas.style.visibility = 'hidden';
var el = paper.text(0, 0, string);
el.attr('font-family', font);
el.attr('font-size', fontSize);
var bBox = el.getBBox();
paper.remove();
return {
width: bBox.width,
height: bBox.height
};
};
module.exports = renderedTextSize;
This seems to work quite nicely, even though it feels a bit hacky to be testing against a magic number (width).

Categories