I am making a google chrome extension, where you press certain buttons, it starts, pauses, or restarts a song. I got it working but there is one problem. When I close the extension, the song stops! I need to know if there is a way around this. I have looked into background scripts and stuff, but I can't get them to work. Please help as this is one of my first google chrome extensions, and I would like to learn more. Thanks for any help you give me!
Html: (popup.html)
<html>
<head>
<link rel="stylesheet" href="styles.css">
<script src="popup.js"></script>
</head>
<body>
<center>
<h1>Music Player</h1>
<h3>Songs:</h3>
<div id="ludicrous_speed">Ludicrous Speed
<audio id="ludicrous" src="songs/ludicrous_speed.mp3" preload="auto"></audio>
<button class="Start" id="StartLudicrous">Start</button>
<button class="Pause" id="PauseLudicrous">Pause</button>
<button class="Restart" id="RestartLudicrous">Restart</button>
</div>
</center>
</body>
</html>
Javascript: (popup.js)
function Start(song) {
song.play();
}
function Pause(song) {
song.pause();
}
function Restart(song) {
song.currentTime = 0;
}
document.addEventListener('DOMContentLoaded', function(){
var Start_Ludicrous = document.getElementById('StartLudicrous');
var Pause_Ludicrous = document.getElementById('PauseLudicrous');
var Restart_Ludicrous = document.getElementById('RestartLudicrous');
Start_Ludicrous.addEventListener('click', function() {
Start(ludicrous);
});
Pause_Ludicrous.addEventListener('click', function() {
Pause(ludicrous);
});
Restart_Ludicrous.addEventListener('click', function() {
Restart(ludicrous);
});
});
CSS: (styles.css)
body {
width:300px;
}
.Start {
background-color: #42f46e;
border-color: #42f46e;
border-radius: 30%;
}
.Pause {
background-color: #f4e349;
border-color: #f4e349;
border-radius: 30%;
}
.Restart {
background-color: #e03838;
border-color: #e03838;
border-radius: 30%;
}
Manifest: (manifest.json)
{
"manifest_version":2,
"name":"Music Player",
"description":"Play Music",
"version":"1.0",
"browser_action":{
"default_popup":"popup.html"
},
"permissions":[
"activeTab"
]
}
The document that popup.html creates exists only as long as it's open.
The moment the popup closes the <audio> element no longer exists.
A background page provides a solution to that - it exists independently of the popup.
You don't normally create a background page's HTML yourself, only provide a bunch of scripts. But nothing stops you from creating a DOM node on the fly:
// background.js
var audio_element = document.createElement("audio");
audio_element.src = "songs/ludicrous_speed.mp3";
audio_element.play();
Now, the popup's code won't be able to directly access the audio_element of the background page; you could do a quick hack job with getBackgroundPage methods, but it's preferable to learn how Messaging works and use chrome.runtime.sendMessage from the popup to control the background.
Related
I have a project where I am creating a spinner page but I am having difficulty integrating the spinner page while I am redirecting to a URL. Basically I have a multiplication program. If the answer is correct it prompts correct and goes to a specific URL(http://stackoverflow.com) and if is incorrect it goes to another URL(http://yahoo.com). Before it actually goes to those pages I would like the spinner that I created to show up first while the pages are loading. Can someone help me with this? Thanks in advance.
Here is my main HTML page(index1.html):
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="stylesheet.css">
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
<meta charset="ISO-8859-1">
<title>A Multiplication Game</title>
</head>
**<script>
window.addEventListener("loader", function(){
var spinner=document.getElementById("spinner");
document.body.removeChild(load_screen);
});
</script>**
<body >
<span id="mathprompt">What is <span id="num1">8</span> multiplied by
<span id="num2">E</span>?
</span>
<br>
<span id="inputrow">
<input type="text" id="inputfield">
<button id="submitbutton">Submit</button>
</span>
**<div class="loader" id="spinner"></div>**
<p id="response"></p>
<script src="script.js" type="text/javascript"></script>
</body>
</html>
Here is my JavaScript code(script.js). As you can see I have declared spinner as a variable but not sure if I should right the function for it here or in HTML:
var num1;
var num2;
var guess;
var answer;
var response;
$(document).ready(function() {
num1=document.getElementById("num1");
num2=document.getElementById("num2");
guess=document.getElementById("inputfield");
response=document.getElementById("response");
**spinner=document.getElementById("spinner");**
$("#submitbutton").click(function(){
checkAnswer();
redirectPage();
});
setNumbers();
});
function setNumbers(){
num1.innerHTML = Math.floor(Math.random() * 10)+1;
num2.innerHTML = Math.floor(Math.random() * 10)+1;
}
function checkAnswer(){
var n1 = parseInt(num1.innerHTML);
var n2 = parseInt(num2.innerHTML);
answer = n1 * n2;
if (parseInt(guess.value) == answer){
response.innerHTML = "Correct!";
} else
response.innerHTML = "Incorrect!";
}
function redirectPage(){
if (parseInt(guess.value) == answer){
window.location.href = "http://stackoverflow.com";
} else{
window.location.href = "http://yahoo.com";
}
}
And here is the code for the spinner in the css(stylesheet.css):
#charset "ISO-8859-1";
#inputrow{
background-color:#80ff80;
}
#mathprompt{
font-size: 34px;
color:orange;
text-align: center;
}
#response{
font-size: 34px;
color:white;
text-align: center;
}
body {
background-color: #8080c0;
text-align: center;
}
**.loader{
border:16px solid #f3f3f3;
border-radius: 50%;
border-top: 16px solid #3498db;
width: 240px;
height: 240px;
animation: spin 2s linear infinite;
margin-left: auto;
margin-right: auto;
text-align:center;
}
#keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}**
You seem to want to detect that an external website is loaded...you cannot detect this, in Javascript you won't have access to the "loaded" event of an external website loaded in a new tab of your browser.
All your can do is display a loading, then doing a "redirect" in javascript.
And when yahoo/stackoverflow page will be loaded (having replaced your website in the browser tab), your loader will obviously have disappeared...is it what you want ?
You have 3 cases :
If you load yahoo/stackoverflow in an iframe embedded in your page, yes you could display a loading and detect that the page is loaded in your iframe (for instance you load a page of your own in the iframe, you can in JS access to the page's content...you load Yahoo/Stackoverflow in the iframe, then when in JS you cannot access to iframe content, it means that the external page is loaded...)
if you are redirecting to the yahoo/stackoverflow page, you will only be able to display a loading before the external pages are beginning to load...
you can try to prefetch the external page, you display a loading, and when the page is loaded, then you redirect to the page...your browser will have cached almost all html elements i think (to check)...
var myPrefetchedPage;
$.ajax({
url: "test.html",
cache: false,
success: function(html){
myPrefetchedPage = html;
}
})
Preloading code in an iframe :
jQuery(document).ready(function ($) {
$app = $('.app');
$app.addClass('loading');
$iframe = $('<iframe>');
$iframe.attr({src: 'http://www.yahoo.fr/'});
$iframe.appendTo($('body'));
// When <iframe> has been loaded, remove loading spinner to reveal <iframe>
// or redirect to the page in your browser tab.
$iframe.load(function() {
$('.app').remove();
// redirect to the real page
window.location.href='http://www.yahoo.fr/';
});
});
So... this is weird?! when i try and use an ACE editor in google chrome in the following context:
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<style>
body {
background-color: rgb(0, 0, 0);
}
.preview {
position: fixed;
margin: 0 auto;
width:800px;
height:600px;
background-color:#3D3D3D;
}
#code {
width:800px;
height:600px;
position: fixed;
margin: 0 auto;
}
</style>
</head>
<body>
<div class="preview" id="preview_layer_1" style="z-index:0;">
nothing much yet
</div>
<div class="preview" id="preview_layer_2" style="z-index:1; background-color:;">
</div>
<div id="code" style="z-index:2;"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/ace/1.2.3/ace.js" type="text/javascript" charset="utf-8"></script>
<script>
$(document).ready(function(){
$("#code").hide();
$(".preview").dblclick(function(){
$("#code").fadeIn();
})
$("#code").dblclick(function(){
$("#code").fadeOut();
})
});
var Editor = ace.edit("code");
var Haxe = ace.createEditSession("","ace/mode/haxe");
var JSON = ace.createEditSession("","ace/mode/json");
Editor.setTheme("ace/theme/monokai");
Editor.setSession(Haxe);
Editor.focus();
</script>
</body>
so like any sane person i go to chrome dev tools to check whats going on and then suddenly it works!
so i reload it repeat the steps without opening devtools and then wait...
but nothing happens! and i don't know where to start the code looks fine to me but i'm sure its just a dumb error that i've made, right?
Thanks in advance
You need to call Editor.resize() when changing position or display of the editor container element, to allow the editor to adapt to the size changes.
It works when opening chrome devtools, because window size changes, and that calls the resize() method.
The following should work:
$(".preview").dblclick(function(){
$("#code").fadeIn();
Editor.resize();
})
This is my first post on SO and my first time making a Chrome Extension. I've read alot of documentation, but I am still unsure how to get this to work. Below are my html and js files. I want to be able to type something in the source box and have the have the word print out in the results area in real time. I have tested this code on my local host so i know it works, but for some reason it is acting up as a chrome extension.
popup.html
<!doctype html>
<html>
<head>
<title>Getting Started Extension Popup</title>
<style>
body {
min-width: 357px;
overflow-x: hidden;
}
img {
margin: 5px;
border: 2px solid black;
vertical-align: middle;
width: 75px;
height: 75px;
}
</style>
<script src="popup.js"></script>
</head>
<body>
<textarea id="source"></textarea>
<div id="result">
</div>
</body>
</html>
Here's the js:
function main() {
document.getElementById('source').keydown(function() {
var source = document.getElementById('source').value;
var outputValue = source.replace(/command/gi, "⌘")
.replace(/tab/gi, "⇥")
.replace(/return/gi, "⏎")
.replace(/option/gi, "⌥")
.replace(/control/gi, "⌃")
.replace(/esc/gi, "⎋")
.replace(/left/gi, "←")
.replace(/down/gi, "↓")
.replace(/up/gi, "↑")
.replace(/right/gi, "→")
.replace(/shift/gi, "⇧")
.replace(/eject/gi, "⏏")
.replace(/caps\s\(lock\)/gi, "⇪")
.replace(/save/gi, "⌘ + S")
.replace(/print/gi, "⌘ + P")
.replace(/find/gi, "⌘ + F");
document.getElementById("result").innerHTML = outputValue;
}
}
1) What wOxxOm said in the comment: element.keydown(function() { ... }) does not exist. This definitely comes from some jQuery code - you could use that if you add it to your extension, or you could use addEventListener.
2) You declare a function main(), but nothing ever calls it. A good place to call it would be a DOMContentLoaded event listener on document:
document.addEventListener("DOMContentLoaded", main);
function main() {
/* ... */
}
I'm starting to learn HTML5+CSS+JS. It was all going fine on my Windows desktop, but when I try doing something on my Linux notebook, no javascript seems to work.
This is the mini tutorial I followed: https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Getting_Started/JavaScript
and this is my page with the result: http://www.lele.bbt.net.ar/prueba01/
(As you can see, the JS is not doing a thing).
// JavaScript demonstration
var changeBg = function(event) {
console.log("method called");
var me = event.target,
square = document.getElementById("square");
square.style.backgroundColor = "#ffaa44";
me.setAttribute("disabled", "disabled");
setTimeout(function() {
clearDemo(me)
}, 2000);
}
function clearDemo(button) {
var square = document.getElementById("square");
square.style.backgroundColor = "transparent";
button.removeAttribute("disabled");
}
var button = document.querySelector("button");
button.addEventListener("click", changeBg);
console.log(button);
#square {
width: 120px;
height: 120px;
border: 2px inset gray;
margin-bottom: 1em;
}
button {
padding: .5em 2em;
}
<!DOCTYPE html>
<html>
<head>
<title>Mozilla CSS Getting Started - JavaScript demonstration</title>
<link rel="stylesheet" type="text/css" href="style.css" />
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<h1>JavaScript sample</h1>
<div id="square"></div>
<button>Click Me</button>
</body>
</html>
(Here it works, but for some reason, not when I do it on my computer).
I don't know if it can be a priviledge problem or something like that (js has read/write priviledges, not execute. But I guess that's how it should be)
Thanks!
I'm pretty sure it's because the script can't find the button.
You load your script before everything else is loaded, which is fine. But you can have problems like this. To avoid this kind of problems you load the JavaScript file after the HTML.
At the moment if you try to print the var "button" you will receive "null".
The Chrome console when you open the page gives you this error:
Uncaught TypeError: Cannot read property 'addEventListener' of null
That means that it is trying to read the property of the button, which is null.
Move the script tag to the very end, just before the closing </body> tag:
<body>
<h1>JavaScript sample</h1>
<div id="square"></div>
<button>Click Me</button>
<script type="text/javascript" src="script.js"></script>
</body>
I used the code I found here.
But it´s still not working out to open my link out of the popup.html in the currently active tab.
popup.html
<!doctype html>
<html>
<style>
body {
min-width: 156px;
max-width: 100%;
position: relative;
vertical-align:middle;
}
div {
margin:1px 1px 1px 1px;
}
</style>
<head>
<title>I-Serv Switcher</title>
<script src="js.js"></script>
</head>
<body>
<script src="js.js"></script>
<div style="width:50px; height:50px; background-color:blue; float:left;">Click.</div>
</body>
</html>
As you can see there is a little blue div. when i add target="_blank", then google opens in a new tab. But adding the following .js should take the link out of the clicked div with href and open it in the active tab.
js.js
var hrefs = document.getElementsByTagName("a");
function openLink() {
var href = this.href;
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
var tab = tabs[0];
chrome.tabs.update(tab.id, {url: href});
});
}
for (var i=0,a; a=hrefs[i]; ++i) {
hrefs[i].addEventListener('click', openLink);
}
the permission "tabs" is given in the manifest.json
What am i doing wrong ?
Did I forget something ?
Your code executes at the moment the <script> tag is read.
The rest of the DOM is not constructed yet; document.getElementsByTagName("a") is, therefore, empty.
To fix this, you need to wrap your code in a DOMContentLoaded event:
document.addEventListener("DOMContentLoaded", function() {
var hrefs = document.getElementsByTagName("a");
/* ... */
});
Note that you can easily debug your popup by right-clicking your extension's button and selecting "Inspect popup"