Firefox addon not always getting video src - javascript

I made trying to make my first addon but I have run into an issue. My addon is an addon to upload images and videos to a website. The images work fine, but with videos, it is a little off. Here is my code:
var contextMenu = require("sdk/context-menu");
var tabs = require("sdk/tabs");
contextMenu.Item({
label: "Upload to domain",
context: contextMenu.SelectorContext("img,video"),
contentScript:'self.on("click", function(node, data){self.postMessage(node.src);});',
onMessage: function(imgSrc){
tabs.open("http://domain.org/upload/?"+imgSrc);
}
});
If you play the video on the right here, the video url gets passed to the onMessage function fine. If you try it here, it doesn't pass a url. They are both webms. I am guessing that it just doesn't work with an html5 player. Am I correct? Is there a workaround for this?

your method of finding source does not always work with video element because, unlike img, the video element's source can be specified as child element source which is what is happening in the second case. To handle that scenario, your code must be something like:
self.on("click", function(node, data){
if(node.src){
self.postMessage(node.src);
}else if(node.nodeName.toUpperCase() === "video".toUpperCase()){
var sources = node.children; // or may be node.querySelector("source");
for(var i in sources){
if(sources[i].src && sources[i].nodeName.toUpperCase() === "source".toUpperCase()){
self.postMessage(node.src);
}
}
}
}

Related

trying to add a multi source video player with more then one video?

Im trying to make a video player work in all browsers. There is
more then one video and every time you click on demo reel it plays the
video and if you click the video 1 the other video plays. How can i
make them both work in all browsers? Here is my html and javascript
html
<video id="myVideo" controls autoplay></video>
<div>
Demo Reel</div>
video 1</div>
</div>
javascript
function changeVid1() {
var changeStuff = document.getElementById("myVideo");
changeStuff.src = "video/demoreel.mp4"
}
function changeVid2() {
var changeStuff = document.getElementById("myVideo");
changeStuff.src = "video/video1.mp4";
}
After you switch the source of the video, you need to run .load() on it to force it to load the new file. Also, you need to provide multiple formats, because there is no video codec supported by all browsers.
First, set up your sources like this:
var sources = [
{
'mp4': 'http://video-js.zencoder.com/oceans-clip.mp4',
'webm':'http://video-js.zencoder.com/oceans-clip.webm',
'ogg':'http://video-js.zencoder.com/oceans-clip.ogv'
}
// as many as you need...
];
Then, your switch function should look like this:
function switchVideo(index) {
var s = sources[index], source, i;
video.innerHTML = '';
for (i in s) {
source = document.createElement('source');
source.src = s[i];
source.setAttribute('type', 'video/' + i);
video.appendChild(source);
}
video.load();
video.play(); //optional
}
See a working demo here.
This gives the browser a list of different formats to try. It will go through each URL until it finds one it likes. Setting the "type" attribute on each source element tells the browser in advance what type of video it is so it can skip the ones it doesn't support. Otherwise, it has to hit the server to retrieve the header and figure out what kind of file it is.
This should work in Firefox going back to 3.5 as long as you provide an ogg/theora file. And it will work in iPads, because you only have one video element on the page at a time. However, auto-play won't work until after the user clicks play manually at least once.
For extra credit, you can append a flash fallback to the video element, after the source tags, for older browsers that don't support html5 video. (i.e., IE < 9 - though you'll need to use jQuery or another shim to replace addEventListener.)

Accept drag & drop of image from another browser window

In Javascript, I know how to set up a drag & drop target that accepts file uploads from the user's computer. How can I set up a drop target that accepts images that are dragged from another website? All I need to know is the URL of the image that they've dragged.
I know this is possible, since Google Docs accepts image drops from other websites. Any idea how they're doing it?
UPDATE:
It looks like there are differences between Chrome on Windows and MacOS. On Windows dataTransfer.getData('Text'); works but not on MacOS. dataTransfer.getData('URL'); should work on both.
OLD answer:
You could define a drop zone:
<div id="dropbox">DropZone => you could drop any image from any page here</div>
and then handle the dragenter, dragexit, dragover and drop events:
var dropbox = document.getElementById('dropbox');
dropbox.addEventListener('dragenter', noopHandler, false);
dropbox.addEventListener('dragexit', noopHandler, false);
dropbox.addEventListener('dragover', noopHandler, false);
dropbox.addEventListener('drop', drop, false);
function noopHandler(evt) {
evt.stopPropagation();
evt.preventDefault();
}
function drop(evt) {
evt.stopPropagation();
evt.preventDefault();
var imageUrl = evt.dataTransfer.getData('Text');
alert(imageUrl);
}
​
It is inside the drop event handler that we are reading the image data from the dataTransfer object as Text. If we dropped an image from some other webpage this text will represent the url of the image.
And here's a live demo.
function drop(evt) {
evt.stopPropagation();
evt.preventDefault();
var imageUrl = evt.dataTransfer.getData('URL'); // instead of 'Text'
alert(imageUrl);
}
Seems to work in Firefox, Safari, and Chrome on Mac. Also works in Firefox, IE, and Chrome in Windows.
Updated fiddle
Although you are able to accept the drag and drop of an image from another website, you are unable to do any processing of it (e.g. converting it to a base64 string using the canvas) (as of 21st August 2014) because of various cross-origin policy issues.
var dt = event.dataTransfer;
var url = dt.getData('url');
if (!url) {
url = dt.getData('text/plain');
if (!url) {
url = dt.getData('text/uri-list');
if (!url) {
// We have tried all that we can to get this url but we can't. Abort mission
return;
}
}
}
Even Google can't get around this - If you use gmail, you can drag and drop an image from another location in to the email body, but all this does is create an <img/> element with its src set to url (from the code above).
However, I've created a plugin that allows you to fake it cross-origin drag and drop. It requires a PHP backend.
Read the article I wrote on it here https://coderwall.com/p/doco6w/html5-cross-origin-drag-and-drop
Here's my solution to the problem: Dropzone js - Drag n Drop file from same page
Please do keep in mind that ability to drag an image from another domain depends on their CORS setup.
Some browsers use text/plain some use text/html as well
This code should pull any text or image source url on the latest Chrome, FF on Mac and PC.
Safari doesn't seem to give the URL so if someone knows how to get it let me know.
I'm still working on IE.
function getAnyText(theevent) {
//see if we have anything in the text or img src tag
var insert_text;
var location = theevent.target;
var etext;
var ehtml;
try {
etext = theevent.dataTransfer.getData("text/plain");
} catch (_error) {}
try {
ehtml = theevent.dataTransfer.getData("text/html");
} catch (_error) {}
if (etext) {
insert_text = etext;
} else if (ehtml) {
object = $('<div/>').html(ehtml).contents();
if (object) {
insert_text = object.closest('img').prop('src');
}
}
if (insert_text) {
insertText(insert_text,location);
}
}
As the other answers correctly state: It normally depends on the CORS-Settings of the server if drag & drop from another browser window is possible (Access-Control-Allow-Origin has to be set).
However I've just found out by chance that it's possible to drap & drop any images from a Firefox (current version 68.0.1) to a Chrome window (current version 76.0.3809) and process it in Javascript, regardless if CORS headers are set or not.
See working example (based on jsfiddle of Darin Dimitrov) which accepts and directly shows images from:
drag and drop from local computer (e.g. from file explorer)
drag and drop from other website, if CORS headers are set, e.g. an image from https://imgur.com/
drag and drop any images from Firefox window to Chrome window:
open jsfiddle demo in Chrome
open e.g. google image search in Firefox and search for any image
click on the image for bigger preview
drag & drop the preview image to the jsfiddle demo in Chrome
However this seems to be kind of a bug of Firefox and therefore I would not rely on this behaviour in an productive application.

ZeroClipboard user script adding in mouse over, working in firefox, but not chrome

I am using zeroclipboard to add a "copy" link to each row in a fairly large list, within a user script. To accomplish that, I using a method similar to the one listed on this page, where the ZeroClipboard.Client() element for each row is created when the user mouses over the row. This is working great in FireFox, but not in Chrome.
Also as a note: I copied the contents of the ZeroClipboard.js file into the user script itself instead of including it in an external file.
Here is the markup that creates the copy button for each element
<span style="color:blue; text-decoration:underline; cursor:pointer" id="copy_'+id+'" class="CopyLink" link="'+url+'" onmouseover="clipboard.add(this)">Copy</span>
Here is the code segment that adds the clipboard's client object:
function main(){
window.clipboard = {
load: function (){
if(!clipboard.initialized){
ZeroClipboard.setMoviePath("http://www.swfcabin.com/swf-files/1343927328.swf");
clipboard.initialized=true;
console.log("Clipboard intialized");
}
},
add: function(element){
clipboard.load();
var clip = new ZeroClipboard.Client();
console.log('Clipboard client loaded: ' + element.id);
clip.glue(element, element.parentNode);
console.log('Clipboard glued: ' + element.id);
clip.setText(element.getAttribute('link'));
console.log('Clipboard text set: ' + element.getAttribute('link'));
clip.addEventListener('complete',function(client,text) {
console.log('Clipboard copied: ' + text);//doesn't fire in chrome
});
clip.addEventListener('load',function(client) {
console.log('Clipboard loaded: ' + element.getAttribute('link'));
});
}
}
//other code in user script including injecting above markup
//as well as contents of ZeroClipboard.js
window.ZeroClipboard = { ... }
}
var script = document.createElement("script");
script.appendChild(document.createTextNode('('+main+')()'));
(document.head || document.body || document.documentElement).appendChild(script);
In this block, every console.log fires in FireFox when I mouse over and click the copy span, but in chrome, all except the 'complete' listener fire. I was able to verify that ZeroClipboard is working in my Chrome by using the example on this page. I am also able to verify that the flash object is being added to the page in the correct location, but it is simply not responding to a click.
Since the zeroclipboard code is no longer being maintained according to the site, I'm hoping someone out there can help me out. I'm thinking there is possibly some issue with dynamically adding the embedded flash objects in chrome on mouseover, or perhaps some difference between user scripts in chrome vs firefox with greasemonkey? Any help would be greatly appreciated, thanks
I'm not sure the reason behind it but I have been running into this on Chrome as well. I had two zeroclipboard implementations, one that was visible on page load, and one that was only visible when the user opened a dialog. The one that was visible on page load worked as expected, but the other one didn't. In order to "solve" the issue, I had to render the zeroclipboard link, set its absolute position to be off the screen (-500 px), then add some javascript to move the link into place when the dialog opens. This is an ugly solution but I think is the only way to get it to work in Chrome. Your case is particularly hairy since you have lots of dynamic zeroclipboards on your page whereas I only had one, but it seems to me that there's no reason this won't work for you.
<!-- <script type="text/javascript" src="http://davidwalsh.name/demo/ZeroClipboard.js"></script> -->
function copyText(fieldName,buttonName){
var fieldNameTemp =fieldName;
var buttonNameTemp =buttonName;
var val = "";
try{
val = navigator.userAgent.toLowerCase();
}catch(e){}
var swfurl = "js/ZeroClipboard.swf";
setTimeout(function () {
ZeroClipboard.setMoviePath(swfurl);
var clip = new ZeroClipboard.Client();
clip.addEventListener('mousedown', function () {
clip.setText(document.getElementById(fieldNameTemp).value);
});
clip.addEventListener('complete', function (client, text) {
try{
if(val.indexOf("opera") > -1 || val.indexOf("msie") > -1 || val.indexOf("safari") > -1 || val.indexOf("chrome") > -1){
alert('Your text has been copied');
}
}catch(e){
alert('Please alert not use on fireFox');
}
});
clip.glue(buttonNameTemp);
}, 2000);
}

How to properly unload/destroy a VIDEO element

I'm working on a realtime media browsing/playback application that uses <video> objects in the browser for playback, when available.
I'm using a mix of straight javascript, and jQuery,
My concern is specifically with memory. The application never reloads in the window, and the user can watch many videos, so memory management becomes a large concern over time. In testing today, I see the memory profile jumping by the size of the video to be streamed with each subsequent load, and never dropping back down to the baseline.
I've tried the following things with the same result:
1 - Empty the parent container containing the created element, eg:
$(container_selector).empty();
2 - Pause and remove children matching 'video', and then empty the parent container:
$(container_selector).children().filter("video").each(function(){
this.pause();
$(this).remove();
});
$(container_selector).empty();
Has anyone else run into this issue, and is there a better way to do this?
It is very tricky to dispose video from the DOM structure. It may lead to browser crashing. Here is the solution that helped me in my project.
var videoElement = document.getElementById('id_of_the_video_element_here');
videoElement.pause();
videoElement.removeAttribute('src'); // empty source
videoElement.load();
this will reset everything, silent without errors !
Edit: Here are the full details as recommended in the Standard: https://html.spec.whatwg.org/multipage/media.html#best-practices-for-authors-using-media-elements
Hope it resolve your query.
This "solution" is reported to work, presumably because it would make those video container objects available for garbage collection (see the note below for a discussion of why delete shouldn't be making a difference). In any case, your results are likely to vary by browser:
$(container_selector).children().filter("video").each(function(){
this.pause(); // can't hurt
delete this; // #sparkey reports that this did the trick (even though it makes no sense!)
$(this).remove(); // this is probably what actually does the trick
});
$(container_selector).empty();
Note: There's no doubt that the delete keyword is specified only to remove properties from objects (as others have pointed out in the comments). Logging this to the console both before and after the delete this line, above, shows the same result each time. delete this should do nothing and make no difference. Yet this answer continues to receive a trickle of votes, and people have reported that omitting delete this makes it stop working. Perhaps there's strangeness in how some browser JS engines implement delete, or an unusual interaction between a browser's delete and what jQuery is doing with this.
So, just be aware, if this answer solves your problem, that if it does work, it's not clear why that's the case, and it's just as likely to stop working for any number of reasons.
To reset the video to Blank without removing it
$("#video-intro").first().attr('src','')
It stops the video
delete(this);
is not a solution. If it worked for x or y it is a browser misbehaviour. Read here:
The delete operator removes a property from an object.
The truth is that some browsers (Firefox for example) will cache in memory the video buffer when autoplay property is on. It is a pain to deal with.
Removing the video tag from the DOM or pausing it can only produce unstable results. You have to unload the buffer.
var video = document.getElementById('video-id');
video.src = "";
My experiment shows that it is done as so but unfortunately this is browser implementation not completely specified by the spec. You do not need to call load() after src change. When changing the src of a video tag you implicitly call a load() on it, this is stated in the W3C spec.
This snippet doesn't do any effecient DOM manipulations (no tag removal) and doesn't fire error event for <video> unlike this answer:
var video = document.getElementById('video');
video.removeAttribute('src');
video.load();
Furthermore, it doesn't fire loadstart event. And it's like it should work - no video, no load start.
Checked in Chrome 54 / FF 49.
Just to clarify for anyone trying this later, the solution was this: (confirmed with h264 videos in Safari 5.0, untested in FF/opera yet)
$(container_selector).children().filter("video").each(function(){
this.pause();
delete(this);
$(this).remove();
});
$(container_selector).empty();
I was having an issue while dynamically loading some videos. I had two sources in my <video> element. One mp4 and the other webm as fallback. So I had to iterate through the <source>'s like so.
function removeMedia(){
let videos = document.getElementsByTagName('video');
for(let vid in videos){
if(typeof videos[vid] == 'object'){
let srcs = videos[vid].getElementsByTagName('source');
videos[vid].pause();
for(let xsrc in srcs){
if(srcs[xsrc].src !== undefined){
srcs[xsrc].src = '';
}
}
videos[vid].load();
videos[vid].parentNode.removeChild(videos[vid]);
}
}
}
ok, here's a simple solution which certainly works:
var bodypage = document.getElementsByTagName('body')[0];
var control_to_remove = document.getElementById('id_of_the_element_here');
bodypage.removeChild(control_to_remove);
According to this bug:
https://bugs.chromium.org/p/chromium/issues/detail?id=255456&can=2&q=255456&colspec=ID%20Pri%20M%20Stars%20ReleaseBlock%20Component%20Status%20Owner%20Summary%20OS%20Modified
this seems to be a memory leak issue in Chrome!
var video = document.getElementById('video');
if (video.firstChild) {
video.removeChild(video.firstChild);
video.load();
}
I've encountered this problem on a more complicated level where we are loading ~80 videos on a page, and having problems with memory management in IE and Edge. I posted our solution on a similar question I asked specifically about our issue: https://stackoverflow.com/a/52119742/1253298
My code did not use a <video> element with a src tag, but instead used multiple <source> children to set a video in multiple formats.
To properly destroy and unload this video, I had to use a combination of multiple answers on this page, which resulted in:
var videoElement = $('#my-video')
videoElement[0].pause() // Pause video
videoElement.empty() // Remove all <source> children
videoElement.load() // Load the now sourceless video
delete videoElement // The call mentioned in other answers
videoElement.remove() // Removing the video element altogether
Hope this helps someone.
Here is an answer on how to close the camera - not only pausing. It is the stream that should be stopped - not the video elements reference:
stream.stop()
Not much complicated. Just put your src to null.
Eg: document.querySelector('#yourVideo').src = null;
It will remove your video src attribute. Done.
This is what I did to solve this problem.
I created 2 video elements (video1 & video2).
After finished using video1, get the source(src) attribute value and then remove video1 from DOM.
Then set video2 source (src) to whatever value you got from video1.
Do not use stream from video1 as it is cached in memory.
Hope this will help.
One solution that worked for me in AngularJS is using below code:
In case you don't want to remove your source url, and reset to start of the video
let videoElement = $document[0].getElementById('video-id');
videoElement.pause();
videoElement.seekable.start(0);
videoElement.load();
And in case you want to remove the source from video tag:
let videoElement = $document[0].getElementById('video-id');
videoElement.pause();
videoElement.src="";
videoElement.load();
Hope someone finds it useful.
I know this is an old question, but I came across the same issue, and tried almost every solution mentioning <video>'s src attribute, and all solutions seemed to have their drawbacks.
In my specify case, besides <video> elements, I am also using <audio> elements at the same time.
I was reading an article at MDN when I realized that dealing with the src attribute could be the wrong thing to do. Instead, I rewrote all my code to append and remove <source> elements to both <video> and <audio> elements.
That was the only way I found that does not trigger a new load or generates error or other undesirable notifications.
This is a minimal/simplified version of the code I am using (tested on Firefox 86 and Chrome 88).
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="en-us">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, minimal-ui, shrink-to-fit=no" />
</head>
<body>
<button type="button" onclick="play()">Play</button>
<button type="button" onclick="stop()">Stop</button>
<video id="myVideo"></video>
<script type="text/javascript">
"use strict";
var myVideo = document.getElementById("myVideo");
myVideo.onloadstart = () => {
console.log("onloadstart");
};
myVideo.onloadeddata = () => {
console.log("onloadeddata");
};
myVideo.onload = () => {
console.log("onload");
};
myVideo.onerror = () => {
console.log("onerror");
};
function play() {
while (myVideo.firstChild)
myVideo.removeChild(myVideo.firstChild);
var source = document.createElement("source");
source.src = "example.mp4";
myVideo.appendChild(source);
myVideo.load();
myVideo.play();
}
function stop() {
while (myVideo.firstChild)
myVideo.removeChild(myVideo.firstChild);
myVideo.load();
}
</script>
</body>
</html>
In my case, i used the solution mentioned above by #toon lite:
Array.from(document.getElementsByTagName('video')).forEach(video => {
video.pause();
video.removeAttribute('src');
video.load();
})
But it occurs the another problem in Chrome browser (version 93):
[Intervention] Blocked attempt to create a WebMediaPlayer as there are too many WebMediaPlayers already in existence. See crbug.com/1144736#c27
I guess it is all about the browser version's limit (mine is too old), anyway i fixed this bug by adding some extra operations:
video.src = '';
video.srcObject = null;
video.remove()
Finally the code looks like:
Array.from(document.getElementsByTagName('video')).forEach(video => {
video.pause();
video.removeAttribute('src'); // video.src = '' works so this line can be deleted
video.load();
video.src = '';
video.srcObject = null;
video.remove()
})

Playing dynamically embedded sound object via Javascript

I need to background load some WAV files for an HTML page using AJAX. I use AJAX to get the details of the WAV files, then use the embed tag, and I can confirm that the files have loaded successfully because when I set autostart to true, the files play. However, I need the files to play only when the user clicks on a button (or an event is fired). The following is my code to preload these files:
function preloadMedia() {
for(var i = 0; i < testQuestions.length; i++) {
var soundEmbed = document.createElement("embed");
soundEmbed.setAttribute("src", "/media/sounds/" + testQuestions[i].mediaFile);
soundEmbed.setAttribute("hidden", true);
soundEmbed.setAttribute("id", testQuestions[i].id);
soundEmbed.setAttribute("autostart", false);
soundEmbed.setAttribute("width", 0);
soundEmbed.setAttribute("height", 0);
soundEmbed.setAttribute("enablejavascript", true);
document.body.appendChild((soundEmbed));
}
}
I use the following code to play the file (based on what sound file that user wants to play)
function soundPlay(which) {
var sounder = document.getElementById(which);
sounder.Play();
}
Something is wrong here, as none of the browsers I have tested on play the files using the code above. There are no errors, and the code just returns.
I would have left it at that (that is - I would have convinced the client to convert all WAV's to MP3 and use MooTools). But I realized that I could play the sound files, which were not dynamically embeded.
Thus, the same soundPlay function would work for a file embeded in the following manner:
<embed src="/media/sounds/hug_sw1.wav" id="sound2" width="0" heigh="0" autostart="false" enablejavascript="true"/>
anywhere within the HTML.
And it plays well in all the browsers.
Anyone have a clue on this? Is this some sort of undocumented security restriction in all the browsers? (Please remember that the files do get preloaded dynamically, as I can confirm by setting the autostart property to true - They all play).
Any help appreciated.
Hmm.. perhaps, you need to wait for the embed object to load its "src" after calling preloadMedia() ?
Are you sure that the media file is loaded when you call soundPlay() ?
i know your question got a bit old by now, but in case you still wonder...
soundEmbed.setAttribute("id", testQuestions[i].id);
you used the same id twice, yet getElementById returns only one element, or false if it doesn't find exactly one matching element.
you could try something like this:
soundEmbed.setAttribute("id", "soundEmbed_"+testQuestions[i].id);
always keep in mind that an id must be unique
Just a tip for more compatibility:
I read here that width and height need to be > 0 for Firefox on MacOS.

Categories

Resources