I am using powerbi embedded. I successfully embed a report into my application using javascript. But I have to update embedded token manually every time.
Now I want to call rest API from my code so that token update automatically.
How to call API from my code to generate token and how to update token when it's going to expire?
My code is :
<html>
<head>
<title>Test</title>
<script src="/Scripts/powerbi.js"></script>
</head>
<body>
<div id="captionArea">
<h1>Power BI Embed test</h1>
</div>
<div id="embedContainer" style="height:500px">
</div>
<script>
(function () {
// Please change these values
var txtAccessToken = 'H4sIAAAAAA...';
var txtEmbedUrl =
'https://app.powerbi.com/reportEmbed?reportId=b21f4f90-e364-4b4c-9281-c5db87cdf3a5&groupId=a4781858-f...';
var txtEmbedReportId = 'b21f4f90-e364-4b4c-9281-c5db87cdf3a5';
var models = window['powerbi-client'].models;
var permissions = models.Permissions.All;
var config = {
type: 'report',
tokenType: models.TokenType.Embed,
accessToken: txtAccessToken,
embedUrl: txtEmbedUrl,
id: txtEmbedReportId,
permissions: permissions,
settings: {
filterPaneEnabled: true,
navContentPaneEnabled: true
}
};
var embedContainer = document.getElementById('embedContainer');
var report = powerbi.embed(embedContainer, config);
}());
</script>
</body>
</html>
I solved it. You can use MSAL or ADAL to generate an access token. I used MSAL.js 1.0 with implicit grant flow: https://learn.microsoft.com/en-us/azure/active-directory/develop/tutorial-v2-javascript-spa
After getting access token you can use ajax to call REST-API to generate embed token.
You can follow this Failed to load response data when tried to get access token from azure using JavaScript
Related
I have almost the same problem that in thread "Adobe PDF Embed API can not change the pdf" and "How to use a variable in Adobe's pdf embed API as URL-value?". which both were addressed by Mr Raymond Camden. The only difference is that I am trying to pass an url to location:url from Flask. Here's the code:
if(window.AdobeDC) displayPDF(urldata);
else document.addEventListener("adobe_dc_view_sdk.ready",
() => displayPDF(urldata));
function displayPDF(urldata) {
document.writeln(urldata[0]);
document.writeln(urldata[1]);
var myURL = urldata[0];
var myFileName = urldata[1];
adobeDCView.previewFile({
content: {
location: {
url: myURL,
},
},
metaData: {
fileName: myFileName
}
}, viewerConfig);
}
Note that I am using Mr Camden trick for dealing with
well-seasoned chicken and nice fresh eggs
.
I can get my 2 parameters going to the html file and to the js file. They are both writelined on the page from the displayPDF(urldata) function. Unfortunately they don't make it to content:location:url and metadata:filename. If I do hardcode these two parameters with existing PDF url and filename I get the result I want to obtain.
What am I doing wrong?
Thanks to anybody who could give me a clue.
All the best,
Pierre-Emmanuel FEGA
zepef#hotmail.com
I've found an answer to my own question. I have posted it on Adobe Community forum as well because "Passing value from external function to document function" because both responses from Shubhanshu Dixit and Raymond Camden have been of great help to me.
My goal was to open a PDF file coming from Azure Blob Storage to use it in an Azure Web App. The app is in Flask. Here's how I've done it and it works great on Azure as well as locally:
FLASK ROUTE
#app.route("/document", methods=['GET', 'POST'])
def document():
# Microsoft blob storage SAS token creation for accessing PDF file in blob storage
blob = get_blob_sas(BLOB_NAME_PATH, STORAGE_ACCOUNT_KEY, BLOB_CONTAINER_NAME, document_to_retrieve)
blob_url = 'https://'+BLOB_NAME_PATH+'.blob.core.windows.net/'+BLOB_CONTAINER_NAME+'/'+document_to_retrieve+'?'+blob
# URL and Filename parameters to send to Adobe Embed API
urldata = [blob_url, document_to_retrieve]
return render_template('view.html', title='SYSTRA Semantic Selected Document', urldata=urldata)
HTML PAGE
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"/>
<meta id="viewport" name="viewport" content="width=device-width, initial-scale=1"/>
<script type="text/javascript" src="{{ url_for('static', filename='view.js') }}"></script>
<script type="text/javascript">
varPDF = previewFile({{urldata|tojson}})
</script>
</head>
<body style="margin: 0px">
<div id="adobe-dc-view"></div>
<script type="text/javascript" src="https://documentcloud.adobe.com/view-sdk/main.js"></script>
</body>
</html>
JAVASCRIPT FUNCTIONS
function previewFile(urldata) {
var myURL = urldata[0];
var myFileName = urldata[1];
if(window.AdobeDC) displayPDF(myURL, myFileName);
else document.addEventListener("adobe_dc_view_sdk.ready",
() => displayPDF(myURL, myFileName));
}
function displayPDF(myURL, myFileName) {
document.write('displayPDF');
const viewerConfig = {
embedMode: "FULL_WINDOW",
defaultViewMode: "FIT_PAGE",
showLeftHandPanel: true,
showAnnotationTools: true,
showDownloadPDF: true,
showPrintPDF: true,
showPageControls: true,
showDisabledSaveButton: true,
downloadWithCredentials: true
};
var adobeDCView = new AdobeDC.View({
clientId: '<CLIENT_ID_KEY_HERE',
divId: "adobe-dc-view"
});
adobeDCView.previewFile({
content: {
location: {
url: myURL,
},
},
metaData: {
fileName: myFileName
}
}, viewerConfig);
}
I hope this helps.
All the best,
Pierre-Emmanuel
I have a site with the following html code:
<div id="captchaDiv"></div>
<script src="https://www.google.com/recaptcha/api.js?onload=getCaptcha&render=explicit&sitekey=My_SITE_KEY"></script>
<script>
window.sd = function(token){
document.writeln(token);
}
getCaptcha = function(){
window.captcha = grecaptcha.render('captchaDiv',{
'sitekey' : My_SITE-KEY,
'callback': windows.sd,
'size':'invisible'
})
}
function onPageLoad(){
grecaptcha.ready(function(){
grecaptcha.execute();
});
}
window.onLoad(onPageLoad());
</script>
Now, when I browse and refresh this page, Google will provide a new token.
I have a test script as follow:
logger.info(RestAssured.get(page_url).then().extract().response().asString())
But instead of getting token, I am getting the page source code. Is there a way to this without creating a page to get the token?
I'm using the PhotoEditorSDK in my application,
but I'm getting the attached error.
in the annex also follows the code that I used to arrive at these results.
It seems to be cross-origin problem
but the SDK has a specific part to it.
I opened called with the support of the company, but so far nothing.
If someone has already experienced this problem, know the reason, or how to solve.
Please help me ;-;
"use stricts";
/*link = http://localhost:8080/editar?&page=1&url=https://photos.google.com/lr/photo/AGj1epXDcMoRlOQ7QcWY9dZ2ALBIqhfJuTSz-ywrilsUhstrZ7wo26XkgDSBk4Jx2nJuIPm3LCFoKuo
*/
var editor;
var vars = getUrlVars();
var page = vars.page;
var url = vars.url;
window.onload = function () {
var container = document.getElementById('editor');
var img = new Image();
img.src = url;
editor = new PhotoEditorSDK.UI.ReactUI({
container: container,
enableUpload: false,
crossOrigin: 'anonymous',
editor: {
image: img,
responsive: true,
enableZoom: false,
controlsOrder: ['transform', 'filter', 'adjustments', 'focus'],
export: {
download: false,
format: 'image/jpeg',
type: PhotoEditorSDK.RenderType.BLOB
},
},
//your license below
license: 'license',
assets: {
baseUrl: '/assets'
},
});
}
function getUrlVars() {
console.log(window.location.href);
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf("#") + 1).split("&");
for (var i = 0; i < hashes.length; i++) {
hash = hashes[i].split("=");
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
<html>
<head>
<script src="/js/jquery-1.11.3.min.js"></script>
<!-- React Dependencies for the SDK UI -->
<script src="js/vendor/react.production.min.js"></script>
<script src="js/vendor/react-dom.production.min.js"></script>
<!-- PhotoEditor SDK-->
<script src="js/PhotoEditorSDK.min.js"></script>
<!-- PhotoEditor SDK UI -->
<script src="js/PhotoEditorSDK.UI.ReactUI.min.js"></script>
<link rel="stylesheet" href="css/PhotoEditorSDK.UI.ReactUI.min.css" />
</head>
<body>
<div id="editor" style="width: 100%; height: 100%; padding-top: 65px;"></div>
<script src="js/editar.js"></script>
</body>
</html>
You need to wait for the image to load before pushing it to PhotoEditorSDK.
You should move your editor = block of code into the img.onload="" method.
Regards,
In the console, there's error message saying that the resource could not be loaded because of same-origin policy.
What you have to do is to enable CORS (Cross-origin resource sharing) for loaded resource. You can see more information here.
However, you may not have controll over loaded resources (e.g. allowing users to add image by specifying external URL).
In this case, you should think about implement a PHP "proxy" that will download image on your server (n.b. same-origin policy is for browsers) and then serve that image to the front-end. You have two options:
Store the image on your server's filesystem and proceed the URL.
Directly serve the content of image to the client, e.g. you could encode the image in base64 and retrieve it via XHR request.
The following is a JavaScript file that searches through YouTube video data using its API. Down at the bottom you'll see the onSearchResponse() function, which calls showResponse(), which in turn displays the search results.
As this code from Codecademy stands, a HUGE amount of information gets printed relating to my search term.
Instead of all that, can I simply display a hyperlink using the title and videoId attributes? How would I go about altering responseString in showResponse() to build that link? Thank you!
// Your use of the YouTube API must comply with the Terms of Service:
// https://developers.google.com/youtube/terms
// 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 link 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: 'clapton'
});
// 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);
console.log(response);
}
Here is the corresponding HTML file:
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="stylesheets/styles.css">
<meta charset="UTF-8">
<title>My YouTube API Demo</title>
</head>
<body>
<section>
<div id="response"></div>
</section>
<script src="javascripts/search-2.js"></script>
<script src="https://apis.google.com/js/client.js?onload=onClientLoad" type="text/javascript"></script>
</body>
</html>
Your advice is much appreciated!
I think it might be what you are exactly trying to do.
function showResponse(response) {
var html = response.items.map(itemToHtml);
document.getElementById('response').innerHTML += html;
}
function itemToHtml(item) {
var title = item.snippet.title;
var vid = item.id.videoId;
return generateHyperlink(title, vid);
}
function generateHyperlink(title, vid) {
return '' + title + '<br/>';
}
This code show up links named title having YouTube video link using videoId.
I am new to JavaScript and Google BigQuery, so please forgive my ignorance. I am trying to write a javascript to collect data from one of the public databases on BigQuery. I found an answer to this at Obtaining BigQuery data from JavaScript code (the code for which I have pasted below) but when I saved the file as .html, replaced the client id and project number with mine, and tried to run it, I get the Authorize button and the page title. I click the Authorize button, and it disappears, but no query is run. Is there something else I was supposed to replace or is there something else I need to make this work? I saved the file as a .html, perhaps I should have saved it with a different extension?
I tried all three ways of creating a client id in the Google developers console and all gave me the same behavior.
I'm sure its just something silly that I am forgetting, but any advice would be greatly appreciated.
Here is the code given by Ryan Boyd, which I am unable to get working properly(which is surely my fault):
<html>
<head>
<script src="https://apis.google.com/js/client.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load('visualization', '1', {packages: ['geochart']});
</script>
<script>
// UPDATE TO USE YOUR PROJECT ID AND CLIENT ID
var project_id = '605902584318';
var client_id = '605902584318.apps.googleusercontent.com';
var config = {
'client_id': client_id,
'scope': 'https://www.googleapis.com/auth/bigquery'
};
function runQuery() {
var request = gapi.client.bigquery.jobs.query({
'projectId': project_id,
'timeoutMs': '30000',
'query': 'SELECT state, AVG(mother_age) AS theav FROM [publicdata:samples.natality] WHERE year=2000 AND ever_born=1 GROUP BY state ORDER BY theav DESC;'
});
request.execute(function(response) {
console.log(response);
var stateValues = [["State", "Age"]];
$.each(response.result.rows, function(i, item) {
var state = item.f[0].v;
var age = parseFloat(item.f[1].v);
var stateValue = [state, age];
stateValues.push(stateValue);
});
var data = google.visualization.arrayToDataTable(stateValues);
var geochart = new google.visualization.GeoChart(
document.getElementById('map'));
geochart.draw(data, {width: 556, height: 347, resolution: "provinces", region: "US"});
});
}
function auth() {
gapi.auth.authorize(config, function() {
gapi.client.load('bigquery', 'v2', runQuery);
$('#client_initiated').html('BigQuery client initiated');
});
$('#auth_button').hide();
}
</script>
</head>
<body>
<h2>Average Mother Age at First Birth in 2000</h2>
<button id="auth_button" onclick="auth();">Authorize</button>
<button id="query_button" style="display:none;" onclick="runQuery();">Run Query</button>
<div id="map"></div>
</body>
</html>
Update: I opened the Developer Tools in Chrome and found this error in the console:
Failed to execute 'postMessage' on 'DOMWindow': The target origin
provided ('file://') does not match the recipient window's origin
('null')
.
I tried editing in my Google Developer console as per these instructions: Google API in Javascript
Still same error.
Looks like you may need to add:
$('#query_button').show();
to the bottom of the auth() function
like so:
function auth() {
gapi.auth.authorize(config, function()
{
gapi.client.load('bigquery', 'v2', runQuery);
$('#client_initiated').html('BigQuery client initiated');
});
$('#auth_button').hide();
$('#query_button').show();
}
Searching for the error you got, I found this page:
Google API in Javascript
Based on the error you're receiving, my guess is that you either do not have your Javascript Origin configured properly on the Google API console you got your Client ID from, and/or you are trying to run your script from the file system instead of through a web server, even one running on localhost. The Google API client, near as I've been able to tell, does not accept authorization requests from the file system or any domain that has not been configured to request authorization under the supplied Client ID. --#citizenslave
It turns out it was a combination of things. I had the Javascript origin not configured properly, I didn't have all the scopes needed for my query, and I couldn't just open the html file in a browser, I needed to create an HTTP server.
So I changed the code to be:
<html>
<head>
<script src="https://apis.google.com/js/client.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load('visualization', '1', {packages: ['geochart']});
</script>
<script>
// UPDATE TO USE YOUR PROJECT ID AND CLIENT ID
var project_id = 'XXXXXXXXXXXX';
var client_id = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.apps.googleusercontent.com';
var config = {
'client_id': client_id,
'scope': 'https://www.googleapis.com/auth/plus.login https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/bigquery'
};
function runQuery() {
var request = gapi.client.bigquery.jobs.query({
'projectId': project_id,
'timeoutMs': '30000',
'query': 'SELECT state, AVG(mother_age) AS theav FROM [publicdata:samples.natality] WHERE year=2000 AND ever_born=1 GROUP BY state ORDER BY theav DESC;'
});
request.execute(function(response) {
console.log(response);
var stateValues = [["State", "Age"]];
$.each(response.result.rows, function(i, item) {
var state = item.f[0].v;
var age = parseFloat(item.f[1].v);
var stateValue = [state, age];
stateValues.push(stateValue);
});
var data = google.visualization.arrayToDataTable(stateValues);
var geochart = new google.visualization.GeoChart(
document.getElementById('map'));
geochart.draw(data, {width: 556, height: 347, resolution: "provinces", region: "US"});
});
}
function auth() {
gapi.auth.authorize(config, function() {
gapi.client.load('bigquery', 'v2', runQuery);
$('#client_initiated').html('BigQuery client initiated');
});
$('#auth_button').hide();
}
</script>
</head>
<body>
<h2>Average Mother Age at First Birth in 2000</h2>
<button id="auth_button" onclick="auth();">Authorize</button>
<button id="query_button" style="display:none;" onclick="runQuery();">Run Query</button>
<div id="map"></div>
</body>
</html>
I fixed my Google Javascript Origins url to be http://localhost:8888/ and my Redirect uri to be http://localhost:8888/oauth2callback, opened a command prompt to run this command from the directory of my html file:
python -m SimpleHTTPServer 8888
and then went to localhost:8888 in my browser and clicked my html file there.
Thanks so much for all the feedback!
It worked perfectly! Now to change the query for my purposes!