简体   繁体   中英

Simple html5 audio player works in browser but not in chrome extension

In the background.js file of my chrome extension i add this :

function loadSong(url) {
    var urlRadio = "mydomain.com";
    document.getElementById("player").src=urlRadio + url;
    document.getElementById("player").load();
    document.getElementById("player").play();
}
window.addEventListener('load', loadSong);

and in html :

<div>
    <audio tabindex="0" id="player" controls="controls">nothing</audio>
    <ul id="playlist">
        <li><a onclick="loadSong('one.mp3')">one</a></li>
        <li><a onclick="loadSong('two.mp3')">two</a></li>
    </ul>
</div>

I added background.js in the homepage , before end tag and in the background part manifest of the chrome extension.

I want to use this player like a webpage and like a chrome extension, so when the code i put it here :

  • "Uncaught TypeError: Cannot set property 'src' of null " at the loading in browser, but i can play songs
  • "Uncaught TypeError: Cannot set property 'src' of null " at the loading in chrome extension, can't play songs

what's the problem ?

There are two errors in ur script. First one is path of audio file and second in ur function call. Here is the sample u can try like this

Html:

<div>
<audio tabindex="0" id="player" controls="controls">nothing</audio>
<ul id="playlist">
    <li><a onclick="loadSong('one.mp3')">one</a></li>
    <li><a onclick="loadSong('two.mp3')">two</a></li>
</ul>
</div>

Script:

function loadSong(url) {
var urlRadio = "path/";
document.getElementById("player").src=urlRadio + url;
document.getElementById("player").load();
document.getElementById("player").play();
}
window.addEventListener('load', loadSong("your audio file name example one.mp3"));

Your First error : Wrong path

var urlRadio = "mydomain.com";
document.getElementById("player").src=urlRadio + url;

in this case (urlRadio + url) the src will become like (mydomain.comone.mp3) this is wrong path it has to be like mydomain.com/one.mp3 .

Your Second error : Function call without passing parameter

 window.addEventListener('load', loadSong);

u have to pass the url value to loadSong function something like this loadSong("one.mp3")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM