I am getting few errors while playing video using YouTube Player Tools - Iframe API.I am getting these 6 errors in the console window of my browser
1.Failed to execute 'postMessage' on 'DOMWindow': The target origin provided ( 'https://www.youtube.com') does not match the recipient window's origin ('http://127.0.0.1').
2.GET chrome-extension://boadgeojelhgndaghljhdicfkmllpafd/cast_sender.js net::ERR_FAILED
3.GET chrome-extension://dliochdbjfkdbacpmhlcpmleaejidimm/cast_sender.js net::ERR_FAILED
4.GET chrome-extension://hfaagokkkhdbgiakmmlclaapfelnkoah/cast_sender.js net::ERR_FAILED
5.GET chrome-extension://fmfcbgogabcbclcofgocippekhfcmgfj/cast_sender.js net::ERR_FAILED
6.GET chrome-extension://enhhojjnijigcajfphajepfemndkmdlo/cast_sender.js net::ERR_FAILED
my index.php is
<html>
<head>
</head>
<body>
<div id='player'></div>
<!--iframe id="player" type="text/html" width="640" height="390"
src="https://www.youtube.com/embed/M7lc1UVf-VE?enablejsapi=1&origin=http://example.com"
frameborder="0"></iframe-->
<script>
var tag = document.createElement('script');
tag.src = "http://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
// 2. This code loads the IFrame Player API code asynchronously.
// 3. This function creates an <iframe> (and YouTube player)
// after the API code downloads.
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
height: '500',
width: '500',
videoId: 'wbLBHYAd0kE',//videos[currentid],
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
// 4. The API will call this function when the video player is ready.
function onPlayerReady(event) {
event.target.playVideo();
}
// 5. The API calls this function when the player's state changes.
// The function indicates that when playing a video (state=1),
// the player should play for six seconds and then stop.
var done = false;
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.PLAYING && !done) {
setTimeout(stopVideo, 10000);
done = true;
}
}
function stopVideo() {
alert();
player.stopVideo();
}
</script>
</body>
</html>
What I need to do to remove these errors?
1st error:
turn
tag.src = "http://www.youtube.com/iframe_api";
into
tag.src = "https://www.youtube.com/iframe_api";
for errors 2-6: This is a known bug with the official Chromecast JavaScript library. Instead of failing silently, it dumps these error messages in all non-Chrome browsers as well as Chrome browsers where the Chromecast extension isn't present.
Related
I'm trying to load a pdf from external server and now I'm getting this error in console.
XMLHttpRequest cannot load
https://mobile.switchitapp.com/uploads/pdf/userGuide.pdf. No
'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://appsdata2.cloudapp.net' is therefore not
allowed access.
How to get rid of this error? I have tried a lot but nothing has worked for me till now please help me out
thanks :)
here is my code
<!DOCTYPE html>
<html>
<head>
<title>PDF.js Learning</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/1.8.472/pdf.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/1.8.472/pdf.worker.js"></script>
<script>
// URL of PDF document
var url = "https://mobile.switchitapp.com/uploads/pdf/userGuide.pdf";
// Asynchronous download PDF
PDFJS.getDocument(url)
.then(function(pdf) {
return pdf.getPage(1);
})
.then(function(page) {
// Set scale (zoom) level
var scale = 1.5;
// Get viewport (dimensions)
var viewport = page.getViewport(scale);
// Get canvas#the-canvas
var canvas = document.getElementById('the-canvas');
// Fetch canvas' 2d context
var context = canvas.getContext('2d');
// Set dimensions to Canvas
canvas.height = viewport.height;
canvas.width = viewport.width;
// Prepare object needed by render method
var renderContext = {
canvasContext: context,
viewport: viewport
};
// Render PDF page
page.render(renderContext);
});
</script>
</head>
<body>
<canvas id="the-canvas"></canvas>
</body>
</html>
Try var url = "https://cors-anywhere.herokuapp.com/https://mobile.switchitapp.com/uploads/pdf/userGuide.pdf"
doesn't work either also
The suggested solution is the comment shall work. Please see:
// URL of PDF document
var url = "https://cors-anywhere.herokuapp.com/" +
"https://mobile.switchitapp.com/uploads/pdf/userGuide.pdf";
// Asynchronous download PDF
PDFJS.getDocument(url)
.then(function(pdf) {
return pdf.getPage(1);
})
.then(function(page) {
// Set scale (zoom) level
var scale = 1.5;
// Get viewport (dimensions)
var viewport = page.getViewport(scale);
// Get canvas#the-canvas
var canvas = document.getElementById('the-canvas');
// Fetch canvas' 2d context
var context = canvas.getContext('2d');
// Set dimensions to Canvas
canvas.height = viewport.height;
canvas.width = viewport.width;
// Prepare object needed by render method
var renderContext = {
canvasContext: context,
viewport: viewport
};
// Render PDF page
page.render(renderContext);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/1.8.472/pdf.js"></script>
<canvas id="the-canvas"></canvas>
Enabling CORS on localhost is no different from enabling on any remote server. See https://enable-cors.org/server.html
Your problem that you cannot do that for remote server, and you really need to enable CORS there instead of localhost. You question is somewhat invalid.
Fiddle
I followed this fiddle. In this it has the video and audio capturing. But it won't let me record the video and send it to php for further processing using ffmpeg and save it.
I want to know that how am i able to record the video and send it to php and save it ?
var btnVideoCapture = document.getElementById('btn-capture-video');
btnVideoCapture.addEventListener('click', showUserMedia, false);
var btnScreenshot = document.getElementById('btn-screenshot');
btnScreenshot.addEventListener('click', snapshot, false);
var btnStopVideo = document.getElementById('btn-stop-video');
btnStopVideo.addEventListener('click', stopUserMedia, false);
var onFailSoHard = function (e) {
console.log('Reeeejected!', e);
};
var video = document.querySelector('video');
var canvas = document.querySelector('canvas');
var ctx = canvas.getContext('2d');
var localMediaStream = null;
function showUserMedia() {
window.URL = window.URL || window.webkitURL;
navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
if (navigator.getUserMedia) {
navigator.getUserMedia({
audio: true,
video: true
}, function (stream) {
video.src = window.URL.createObjectURL(stream);
video.controls = true;
localMediaStream = stream;
}, onFailSoHard);
// console.log('Good to go!');
} else {
video.src = 'somevideo.webm'; // fallback.
//console.log('getUserMedia() is not supported in your browser');
}
}
function snapshot() {
canvas.width = video.videoWidth;
canvas.height = video.videoHeight;
if (localMediaStream) {
ctx.drawImage(video, 0, 0);
// "image/webp" works in Chrome 18. In other browsers, this will fall back to image/png.
document.querySelector('img').src = canvas.toDataURL('image/webp');
}
}
function stopUserMedia() {
video.pause();
localMediaStream.stop();
video.src = '';
}
The code you posted only accesses the webcam and displays the video stream in the <video> element (showUserMedia() function). It doesn't record the video or POSTs the data to a web server.
To record the video (and audio) you need to use the Media Recorder API which is now supported by Chrome (49+) and Firefox(30+). Both browsers record to .webm and you can POST the file to a web server for further processing.
This article covers the spec in detail and here's a live demo + GitHub project.
Take a look at RecordRTC
You may want to take a look at this too: How to record webcam and audio using webRTC and a server-based Peer connection
I think this serves your specific need: https://github.com/muaz-khan/WebRTC-Experiment/tree/master/RecordRTC/RecordRTC-to-PHP
Here's an example of recording video and audio: opentokrtc.com
1- First you would do recording using javascript
2- then set a hidden mutipart hidden form in page
3- When a video has recorded then you trigger an event which render the recorded video to form.
4 - then here you can manually submit this video to PHP script
I need a pop up (facebook like share box) to be displayed when the the youtube video stops.
I already have lots of videos on my wordpress website. I need this to work for all my previous videos.
I've already tried this from another post here:
<html>
<head>
<title>YT Test</title>
<script type="text/javascript">
<!--
// 2. This code loads the IFrame Player API code asynchronously.
var tag = document.createElement('script');
tag.src = "http://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
// 3. This function creates an <iframe> (and YouTube player) after the API code downloads.
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
height: '390',
width: '640',
videoId: 'ecccag3L-yw',
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
// The API will call this function when the video player is ready.
function onPlayerReady(event) { /* do nothing yet */ }
// The API calls this function when the player's state changes.
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.ENDED) {
// insert appropriate modal (or whatever) below
alert('I hope you enjoyed the video')
}
}
-->
</script>
</head>
<body>
<div id="player"></div>
</body>
<html>
isn't helping. This works only for one video. ecccag3L-yw in this case.
Can someone help me do this right?
here is an example of what I need. http://www.broascadilie.ro/index.php/video/item/29208-c%C3%A2nd-ea-are-chef-%C8%99i-tu-nu-when-she-is-in-the-mood-and-he-isnt
after the video ends, a pop up comes up for users to like and/or share.
This one isn't hard. You need to change videoId: 'ecccag3L-yw' to videoId: '<?php echo $id?>'
Also you need to make sure that in the $id variable is stored your video ID. Since you are using wordpress you should just make a connection to the database and get the value you are interested.
So about after the <title></title>
When I attempt to load a Google Chart in node.js, nothing happens.
I tried loading the first example from the line chart docs in both zombie.js and jsdom, but the chart never loads in either case.
The end goal is to retrieve the SVG data of the generated chart for export into an image or PDF. So if an alternate method (server side using node.js or PHP) to achieve this is possible, I'm open to suggestions.
NOTE: I have successfully generated a images of a few charts using gChartPhp, but the requirements of this project state that the embedded version be the interactive version provided by the current API and the exported version be visually IDENTICAL to the embedded one (without being interactive, obviously).
Edit: I tagged PhantomJS, since that is the solution with which I ultimately went.
Sorry for the lack of links, but the spam prevention mechanism will only allow me to post 2.
I'm 8 years late but I've just released an open-source project Google Charts Node that renders chart images in Puppeteer (somewhat of a successor to the original PhantomJS solution).
google-charts-node is available as an NPM library and can be used like so:
const GoogleChartsNode = require('google-charts-node');
function drawChart() {
// Set up your chart here, just like in the browser
// ...
const chart = new google.visualization.BarChart(container);
chart.draw(data, options);
}
// Render the chart to image
const image = await GoogleChartsNode.render(drawChart, {
width: 400,
height: 300,
});
Now you can save this image buffer as a file or return it as an HTTP response, etc.
It was pretty straightforward to create this. The main caveats were:
Not all charts support getImageURI, so I fall back to puppeteer to take a screenshot when this happens.
It's slow! But if you must use Google Charts as a requirement, you don't really have an alternative. This problem can be mitigated with enough cloud compute resources.
You can view the full source at the Github project, but here's the raw puppeteer flow if you want to do it yourself:
async function render() {
// Puppeteer setup
const browser = await puppeteer.launch();
const page = await browser.newPage();
// Add the chart
await page.setContent(`...Insert your Google Charts code here...`);
// Use getImageURI if available (not all charts support)
const imageBase64 = await page.evaluate(() => {
if (!window.chart || typeof window.chart.getImageURI === 'undefined') {
return null;
}
return window.chart.getImageURI();
});
let buf;
if (imageBase64) {
buf = Buffer.from(imageBase64.slice('data:image/png;base64,'.length), 'base64');
} else {
// getImageURI was not available - take a screenshot using puppeteer
const elt = await page.$('#chart_div');
buf = await elt.screenshot();
}
await browser.close();
return buf;
}
It wasn't the ideal solution, but I found an alternative to node.js for accomplishing the same end goal in PhantomJS. Simply create an HTML file containing the chart (test.html) and like node.js, create a JS file containing your code (test.js). Then run your JS file with PhantomJS.
In your JS file, open your HTML file as a webpage, then render it, either saving the image buffer to a file:
var page = require('webpage').create();
page.open('test.html', function () {
page.render('test.png');
phantom.exit();
});
Then run it:
phantomjs test.js
To dynamically create a chart, create the following JS file (test2.js):
var system = require('system');
var page = require('webpage').create();
page.onCallback = function(data)
{
page.clipRect = data.clipRect;
page.render('test.png');
phantom.exit();
};
page.includeJs('http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js', function()
{
page.includeJs('https://www.google.com/jsapi', function()
{
page.evaluate(function(chartType, data_json, options_json)
{
var div = $('<div />').attr('id', 'chart').width(900).height(500).appendTo($('body'));
google.load("visualization", "1",
{
packages:[chartType == 'GeoChart' ? 'geochart' : 'corechart'],
callback: function()
{
data_arr = $.parseJSON(data_json);
data = google.visualization.arrayToDataTable(data_arr);
options = $.parseJSON(options_json);
chart = new google.visualization[chartType]($(div).get(0));
google.visualization.events.addListener(chart, 'ready', function()
{
window.callPhantom(
{
clipRect: $(div).get(0).getBoundingClientRect()
});
});
chart.draw(data, options);
}
});
}, system.args[1], system.args[2], system.args[3]);
});
});
Then run it:
phantomjs test2.js LineChart '[["Date","Steve","David","Other"],["Dec 31",8,5,3],["Jan 1",7,10,4],["Jan 2",9,4,3],["Jan 3",7,5,3]]' '{"hAxis.slantedText":true}'
phantomjs test2.js PieChart '[["Employee","Calls"],["Steve",31],["David",24],["Other",13]]' '{"is3D":true}'
phantomjs test2.js GeoChart '[["State","Calls"],["US-CA",7],["US-TX",5],["US-FL",4],["US-NY",8]]' '{"region":"US","resolution":"provinces"}'
To get the image data from an external script, make a copy of test2.js (test3.js) and change
page.render('test.png');
to
console.log(page.renderBase64('png'));
Then call it (from PHP, for example):
<?php
$data = array(
array("Employee", "Calls"),
array("Steve", 31),
array("David", 24),
array("Other", 13)
);
$options = array(
"is3D" => true
);
$command = "phantomjs test3.js PieChart '" . json_encode($data) . "' '" . json_encode($options) . "'";
unset($output);
$result = exec($command, $output);
$base64_image = implode("\n", $output);
$image = base64_decode($base64_image);
?>
NOTE: Looking back on this whole process, the problem I was having with node.js was possibly that I didn't setup callbacks or timeouts to wait until the charts were "ready".
I am opening my blog page in my website. The problem is I can give a width to an iframe but the height should be dynamic so that there is no scrollbar in the iframe, and it looks like a single page...
I have tried various JavaScript code to calculate the height of the content but all of them give an access denied permission error and is of no use.
<iframe src="http://bagtheplanet.blogspot.com/" name="ifrm" id="ifrm" width="1024px" ></iframe>
Can we use Ajax to calculate height or maybe using PHP?
To directly answer your two subquestions: No, you cannot do this with Ajax, nor can you calculate it with PHP.
What I have done in the past is use a trigger from the iframe'd page in window.onload (NOT domready, as it can take a while for images to load) to pass the page's body height to the parent.
<body onload='parent.resizeIframe(document.body.scrollHeight)'>
Then the parent.resizeIframe looks like this:
function resizeIframe(newHeight)
{
document.getElementById('blogIframe').style.height = parseInt(newHeight,10) + 10 + 'px';
}
Et voila, you have a robust resizer that triggers once the page is fully rendered with no nasty contentdocument vs contentWindow fiddling :)
Sure, now people will see your iframe at default height first, but this can be easily handled by hiding your iframe at first and just showing a 'loading' image. Then, when the resizeIframe function kicks in, put two extra lines in there that will hide the loading image, and show the iframe for that faux Ajax look.
Of course, this only works from the same domain, so you may want to have a proxy PHP script to embed this stuff, and once you go there, you might as well just embed your blog's RSS feed directly into your site with PHP.
You can do this with JavaScript.
document.getElementById('foo').height = document.getElementById('foo').contentWindow.document.body.scrollHeight + "px";
Fitting IFRAME contents is kind of an easy thing to find on Google. Here's one solution:
<script type="text/javascript">
function autoIframe(frameId) {
try {
frame = document.getElementById(frameId);
innerDoc = (frame.contentDocument) ? frame.contentDocument : frame.contentWindow.document;
objToResize = (frame.style) ? frame.style : frame;
objToResize.height = innerDoc.body.scrollHeight + 10;
}
catch(err) {
window.status = err.message;
}
}
</script>
This of course doesn't solve the cross-domain problem you are having... Setting document.domain might help if these sites are in the same place. I don't think there is a solution if you are iframe-ing random sites.
Here's my solution to the problem using MooTools which works in Firefox 3.6, Safari 4.0.4 and Internet Explorer 7:
var iframe_container = $('iframe_container_id');
var iframe_style = {
height: 300,
width: '100%'
};
if (!Browser.Engine.trident) {
// IE has hasLayout issues if iframe display is none, so don't use the loading class
iframe_container.addClass('loading');
iframe_style.display = 'none';
}
this.iframe = new IFrame({
frameBorder: 0,
src: "http://www.youriframeurl.com/",
styles: iframe_style,
events: {
'load': function() {
var innerDoc = (this.contentDocument) ? this.contentDocument : this.contentWindow.document;
var h = this.measure(function(){
return innerDoc.body.scrollHeight;
});
this.setStyles({
height: h.toInt(),
display: 'block'
});
if (!Browser.Engine.trident) {
iframe_container.removeClass('loading');
}
}
}
}).inject(iframe_container);
Style the "loading" class to show an Ajax loading graphic in the middle of the iframe container. Then for browsers other than Internet Explorer, it will display the full height IFRAME once the loading of its content is complete and remove the loading graphic.
Below is my onload event handler.
I use an IFRAME within a jQuery UI dialog. Different usages will need some adjustments.
This seems to do the trick for me (for now) in Internet Explorer 8 and Firefox 3.5.
It might need some extra tweaking, but the general idea should be clear.
function onLoadDialog(frame) {
try {
var body = frame.contentDocument.body;
var $body = $(body);
var $frame = $(frame);
var contentDiv = frame.parentNode;
var $contentDiv = $(contentDiv);
var savedShow = $contentDiv.dialog('option', 'show');
var position = $contentDiv.dialog('option', 'position');
// disable show effect to enable re-positioning (UI bug?)
$contentDiv.dialog('option', 'show', null);
// show dialog, otherwise sizing won't work
$contentDiv.dialog('open');
// Maximize frame width in order to determine minimal scrollHeight
$frame.css('width', $contentDiv.dialog('option', 'maxWidth') -
contentDiv.offsetWidth + frame.offsetWidth);
var minScrollHeight = body.scrollHeight;
var maxWidth = body.offsetWidth;
var minWidth = 0;
// decrease frame width until scrollHeight starts to grow (wrapping)
while (Math.abs(maxWidth - minWidth) > 10) {
var width = minWidth + Math.ceil((maxWidth - minWidth) / 2);
$body.css('width', width);
if (body.scrollHeight > minScrollHeight) {
minWidth = width;
} else {
maxWidth = width;
}
}
$frame.css('width', maxWidth);
// use maximum height to avoid vertical scrollbar (if possible)
var maxHeight = $contentDiv.dialog('option', 'maxHeight')
$frame.css('height', maxHeight);
$body.css('width', '');
// correct for vertical scrollbar (if necessary)
while (body.clientWidth < maxWidth) {
$frame.css('width', maxWidth + (maxWidth - body.clientWidth));
}
var minScrollWidth = body.scrollWidth;
var minHeight = Math.min(minScrollHeight, maxHeight);
// descrease frame height until scrollWidth decreases (wrapping)
while (Math.abs(maxHeight - minHeight) > 10) {
var height = minHeight + Math.ceil((maxHeight - minHeight) / 2);
$body.css('height', height);
if (body.scrollWidth < minScrollWidth) {
minHeight = height;
} else {
maxHeight = height;
}
}
$frame.css('height', maxHeight);
$body.css('height', '');
// reset widths to 'auto' where possible
$contentDiv.css('width', 'auto');
$contentDiv.css('height', 'auto');
$contentDiv.dialog('option', 'width', 'auto');
// re-position the dialog
$contentDiv.dialog('option', 'position', position);
// hide dialog
$contentDiv.dialog('close');
// restore show effect
$contentDiv.dialog('option', 'show', savedShow);
// open using show effect
$contentDiv.dialog('open');
// remove show effect for consecutive requests
$contentDiv.dialog('option', 'show', null);
return;
}
//An error is raised if the IFrame domain != its container's domain
catch (e) {
window.status = 'Error: ' + e.number + '; ' + e.description;
alert('Error: ' + e.number + '; ' + e.description);
}
};
#SchizoDuckie's answer is very elegant and lightweight, but due to Webkit's lack of implementation for scrollHeight (see here), does not work on Webkit-based browsers (Safari, Chrome, various and sundry mobile platforms).
For this basic idea to work on Webkit along with Gecko and Trident browsers, one need only replace
<body onload='parent.resizeIframe(document.body.scrollHeight)'>
with
<body onload='parent.resizeIframe(document.body.offsetHeight)'>
So long as everything is on the same domain, this works quite well.
I just spent the better part of 3 days wrestling with this. I'm working on an application that loads other applications into itself while maintaining a fixed header and a fixed footer. Here's what I've come up with. (I also used EasyXDM, with success, but pulled it out later to use this solution.)
Make sure to run this code AFTER the <iframe> exists in the DOM. Put it into the page that pulls in the iframe (the parent).
// get the iframe
var theFrame = $("#myIframe");
// set its height to the height of the window minus the combined height of fixed header and footer
theFrame.height(Number($(window).height()) - 80);
function resizeIframe() {
theFrame.height(Number($(window).height()) - 80);
}
// setup a resize method to fire off resizeIframe.
// use timeout to filter out unnecessary firing.
var TO = false;
$(window).resize(function() {
if (TO !== false) clearTimeout(TO);
TO = setTimeout(resizeIframe, 500); //500 is time in miliseconds
});
The trick is to acquire all the necessary iframe events from an external script. For instance, you have a script which creates the iFrame using document.createElement; in this same script you temporarily have access to the contents of the iFrame.
var dFrame = document.createElement("iframe");
dFrame.src = "http://www.example.com";
// Acquire onload and resize the iframe
dFrame.onload = function()
{
// Setting the content window's resize function tells us when we've changed the height of the internal document
// It also only needs to do what onload does, so just have it call onload
dFrame.contentWindow.onresize = function() { dFrame.onload() };
dFrame.style.height = dFrame.contentWindow.document.body.scrollHeight + "px";
}
window.onresize = function() {
dFrame.onload();
}
This works because dFrame stays in scope in those functions, giving you access to the external iFrame element from within the scope of the frame, allowing you to see the actual document height and expand it as necessary. This example will work in firefox but nowhere else; I could give you the workarounds, but you can figure out the rest ;)
Try this, you can change for even when you want. this example use jQuery.
$('#iframe').live('mousemove', function (event) {
var theFrame = $(this, parent.document.body);
this.height($(document.body).height() - 350);
});
Try using scrolling=no attribute on the iframe tag. Mozilla also has an overflow-x and overflow-y CSS property you may look into.
In terms of the height, you could also try height=100% on the iframe tag.