【发布时间】:2016-08-30 03:17:36
【问题描述】:
我正在尝试为 Firefox 制作一个 Web 扩展,它将在新选项卡中打开一个 .webm 文件,并强制它自动循环。但是我在新页面上的脚本部分没有执行。它不会抛出错误或任何东西,它只是不执行。我一直在使用 Firefox 的内置调试控制台 (ctrl+shift+alt+i) 对其进行调试。
如果我直接在 Firefox 中打开网页,效果很好(例如,使用 alt+o 而不是使用网络扩展来加载它)。
我也不能使用window.open(),所以我不得不使用chrome.tabs.create()。不知道有没有关系。
这是我的代码...
manifest.js
{
"manifest_version": 2,
"name": "LoopWebm",
"version": "1.0",
"description": "Adds a context menu option to videos that allows you to open them in a new tab or window (based on User Preferences), where it will play and auto-loop. Intended for use with .webm videos.",
"icons": {
"16": "icons/loop16.png",
"32": "icons/loop32.png",
"48": "icons/loop48.png"
},
"background": {
"scripts": ["background.js"]
},
"permissions": [
"contextMenus",
"tabs",
"activeTab",
"<all_urls>"
]
}
还有 background.js
function onCreated(n) {
if (chrome.runtime.lastError) {
console.log("error creating item:" + chrome.runtime.lastError);
} else {
console.log("item created successfully");
}
}
function onRemoved() {
if (chrome.runtime.lastError) {
console.log("error removing item:" + chrome.runtime.lastError);
} else {
console.log("item removed successfully");
}
}
//add my extension to the .webm (and other videos) context menu
chrome.contextMenus.create({
id: "ShorkLoop",
title: "ShorkLooper",
contexts: ["video"]
}, onCreated);
//add a listener to this extension's context menu
chrome.contextMenus.onClicked.addListener(function(info, tab) {
console.log("got to the background listener!");
var newIndex = tab.id; //tab.id is 1-based, tabs.create is 0-based. Thus this puts newIndex in the next spot
//window.open() doesn't work here. Doesn't even throw an error in the debugger or stop the function.
chrome.tabs.create({ "url": chrome.extension.getURL("myPage.html?insrc=" + info.srcUrl), "index":newIndex});
chrome.tabs.executeScript(newIndex, {code:'document.getElementById("Video1").src = "http://video.webmfiles.org/elephants-dream.webm";'});
console.log("got to the end of the background listener!");
});
和 myPage.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script type="text/javascript">
function videoSwitch()
{
console.log("Switching video!");
//switches the video's source
//works fine if I load it on its own
//but doesn't work when used in a webextension
document.getElementById("Video1").src = "http://video.webmfiles.org/elephants-dream.webm";
}
</script>
</head>
<body onload="videoSwitch()" bgcolor=#222222>
<video id="Video1" style="display:block; margin: 0 auto;" controls autoplay loop src='http://video.webmfiles.org/big-buck-bunny_trailer.webm'>
</video>
</body>
</html>
编辑:在 Duskwuff 的链接之后,我通过创建一个新的 .js 文件使其工作。我将标签放在 HTML 的头部,将 videoSwitch() 移动到新的 .js 文件中,并添加了
document.addEventListener('DOMContentLoaded', function() {
videoSwitch();
});
【问题讨论】:
标签: javascript html firefox