Basically, there is a specific website I visit that I keep a userscript auto-refresh set on a timer. This specific page changes content every now and then upon being refreshed. I want a sound to be played whenever the page gets refreshed and any page changes occur.
Here's the code I've currently gathered, but I still need a few things to get it running properly:
// ==UserScript==
// #name Auto-Refresh
// #include https://www.prolific.ac/studies
// ==/UserScript==
//--- https://stackoverflow.com/questions/25484978/i-want-a-simple-greasemonkey-script-to-reload-the-page-every-minute
setTimeout(function(){ location.reload(); }, 20*1000);
var player = document.createElement('audio');
player.src = 'https://notificationsounds.com/soundfiles/a86c450b76fb8c371afead6410d55534/file-sounds-1108-slow-spring-board.mp3';
player.preload = 'auto';
// Play a sound with condition and then player.play()
So basically the rest of the script would be "if page change occurs (after refresh), then play sound." This is where I'm having trouble.
I've been using this thread as a guide: How to monitor a static HTML page for changes with Greasemonkey? Use a hash? But I'm not quite sure which method would work best. Any and all advice would be deeply appreciated. Thanks in advance.
In my experience you want to check for changes in specific elements, not the HTML of the entire page because there are often technical parts of the page that will change (timestamps, counters, random generated IDs, ads). So I have used jQuery to find the pieces which I then check for changes.
I guess you could check for changes in entire parts of page by doing something like this:
var player = document.createElement('audio');
player.src = 'https://notificationsounds.com/soundfiles/a86c450b76fb8c371afead6410d55534/file-sounds-1108-slow-spring-board.mp3';
player.preload = 'auto';
// First you store the content
var initialContent = $('.articles-section').html();
// Then next time you compare that content to the newly retrieved content
var newContent = $('.articles-section').html();
if (newContent !== initialContent) {
player.play();
}
You will have to use some kind of persistent storage, I guess you can use localStorage for that. See HTML5 Web Storage.
This part
var player = document.createElement('audio');
player.src = 'https://notificationsounds.com/soundfiles/a86c450b76fb8c371afead6410d55534/file-sounds-1108-slow-spring-board.mp3';
player.preload = 'auto';
only worked for me when I did
player.play() instead of player.preload = 'auto'
Related
I'm working on something where the user hovers over a video to trigger it playing. When they hover over a different video, this new video starts playing and stops the others.
I'm using Vimeo and their Froogaloop library ( not too relevant here, could also be video tags, mainly concerned with the caching of the selectors ).
This code works fine, but I know it's not as optimised as it should be, it uses multiple selectors each time the hover function is called which I don't want to do. Can I improve this code so that it doesn't do this? Or is it Ok to keep calling the jQuery selectors like this in modern browsers now?
Here is a simplified working demo
function hoverVid() {
var frame = $(this).find('iframe');
var player = $f(frame[0]);
player.api('play');
var vids = $('.vid-row iframe').not(frame);
vids.each(function(index) {
var frame = $(this);
var player = $f(frame[0]);
player.api('pause');
});
}
$('.vid-row').hover(hoverVid);
Cheers :]
I improved it a bit - As per #GerardCuadras comment, removed the need for using the .not() filter by simply pausing all the videos, then playing the desired one.
This allowed me to cache the list of iframes. I also optimised the selector to use an #id and .find().
JSBin
var vidz = $('#vidz').find('iframe');
function hoverVid(e){
vidz.each(function( index ){
var frame = $(this);
var player = $f(frame[0]);
player.api('pause');
});
var frame = $(this).find('iframe');
var player = $f(frame[0]);
player.api('play');
}
$('.vid-row').hover(hoverVid);
I am using a Javascript code to detect if a video is loaded.
Once it is loaded I want to add an autoplay attribute to the <video> tag to make it play but I can't find a way to add that attribute. Here is the code I use:
window.addEventListener('load', function() {
var video = document.querySelector('#bgvid');
var div = document.getElementById('#bgvid');
function checkLoad() {
if (video.readyState === 4) {
alert('video is loaded')
video.setAttribute("autoplay")
} else {
setTimeout(checkLoad, 100);
}
}
checkLoad();
}, false);
******************* THE SOLUTION ********************
First, thanks DontVoteMeDown for the help.
Proper code should be:
document.getElementById('bgvid').addEventListener('canplaythrough', function() {
this.play();
});
Why not add the attribute to the tag? From the docs:
autoplay: (...) the video will automatically begin to play back as soon as it can do so without stopping to finish loading the data.
So I presume (not sure, indeed) that the video will start playing as soon it loads a part of the video.
Anyway, if you still want to add the attribute, the video tag has some Events, from docs:
canplay: Sent when enough data is available that the media can be played, at least for a couple of frames;
canplaythrough: Sent when the ready state changes to CAN_PLAY_THROUGH, indicating that the entire media can be played without interruption(...);
So you can use one of those events to set the attribute, e.g:
document.getElementById('bgvid').addEventListener('canplay', function() {
this.setAttribute("autoplay", "autoplay");
});
With this you can avoid using timeouts, which isn't the best approach.
with autoplay enabled there is no need to check its load state, the video will simply play when it can, is loaded.
video.autoplay = true;
Look here
I've made a site that randomizes HTML videos or images just to practice my javascript.
I am trying to make it so that each time a video is randomized the URL location will change to represent the new video, this way users would be able to link directly to a video that was randomized.
Currently it only displays a static url that does not change whenever content is loaded.
Here is the obligatory codepen
Codepen
function chooseRandomVideoFromList() {
var i = Math.floor(Math.random() * currentList.length);
var video = currentList[i];
var $video = $('video');
// clear
$video.html('');
// <source src="" type="">
video.sources.forEach(function (source) {
var $source = $('<source>').attr('type', source.type).attr('src', source.src);
$video.append($source);
});
Any help or advice would be greatly appreciated, i've read the documentation and I am still stumped :S
Thanks guys!
You cannot directly write on the window.location.href property, but you may change your sites url with the html5 history api and pushstate.
Example:
history.pushState({}, "Stackoverflow", "http://stackoverflow.com");
This should work in all modern browsers, see: http://caniuse.com/#search=pushstate
More information on this topic could be found here: https://developer.mozilla.org/de/docs/Web/Guide/DOM/Manipulating_the_browser_history
Though keep in mind you need also to listen on popstate events if you want the users to be able to use their browsers back and forward buttons. Also your server side code needs to handle the urls.
If you need to support older browsers or don't want the server side to be involved you could set the window.location.hash property instead which does not change the url itself but let you change the hash part of the current url, for example:
window.location.hash = "uri=stackoverflow.com";
This way you might store the Index of the video currently shown. When loading the page you might want to check if there's a value in "window.location.hash" and if it is a valid index for your videoFiles. If so you should play that video.
Example (insert in your starting code):
if (window.location.hash !== "") {
showSpecificVideoFromList(window.location.hash);
}
And this one in your chooseRandomVideoFromList:
window.location.hash=i;
Then implement your showSpecificVideoFromList in order to show the given index (and check for validity)
I have and audio that is being played and I want to stop it from playing once the user clicks on a button. I have tried popcorn.mute(), but it does not give the result I want. I want something like popcorn.stop();
If you want to really destroy the video, you need to make sure that a) it's not playing and b) there are no references to it anywhere in memory, including the DOM. That way, the Javascript engine can garbage-collect it. Just to be extra thorough, we'll clear out the src.
var video = popcorn.media; //grab a reference to the actual video element
//make sure it's not playing
video.pause();
//clean up popcorn
popcorn.destroy();
popcorn.media = null; //popcorn should probably do this in destroy, but it doesn't
//clear the src, Make sure it's no longer using the network.
video.src = '';
video.load();
//remove from the DOM. You won't see it anymore.
if (video.parentNode) {
video.parentNode.removeChild(video);
}
You'll also want to clear any other references you may have to the video, and it probably couldn't hurt to remove any event listeners you may have added, whether directly on the video element or through Popcorn.
I have a HTML page with an image in it.
When I roll-over the image with my mouse it plays an audio file.
I have 4 different audio files, and each time I roll-over the image I need it to play the next audio-file in the sequence.
I've got it playing one audio-file back ok, but how do I get it calling the next audio-file in the queue?
Its likely you just need to make a javascript function on the webpage to handle this. Without seeing your codes I can't really give you a good example. Here is what I would do. Within a a script tag or head javascript:
var current = 0;
var musicList = ["file1.wav", "file2.wav" , ...];
function playSound()
{
// Code to play audio file
// you don't need to bother with <audio> elements.
// HTML 5 lets you access audio API directly
// buffers automatically when created
var snd = new Audio(musicList[current]);
snd.play();
// code to increment and current counter (depending on musicList size)
current++;
current = current % musicList.length;
}
Within your HTML, you can just rely on javascript to do the work by using the onmouseover or onmouseout tag.
<img onmouseover="playSound();" src="smiley.gif" alt="Smiley">