我试图为Firefox创建一个Web扩展程序,它将在新标签页中打开.webm文件,并强制它自动循环。但是我的脚本在新页面上的部分并没有执行。它不会抛出错误或任何东西,它只是没有执行。我使用Firefox的内置调试控制台(ctrl + shift + alt + i)进行了调试。
如果我直接在firefox中打开网页(例如,通过使用alt + o而不是使用网络扩展来加载它),它可以正常工作。
我也不能使用window.open(),所以我不得不使用chrome.tabs.create()。我不知道这是否相关。
这是我的代码......
manifest.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!");
});
and background.js
<!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>
和myPage.html
document.addEventListener('DOMContentLoaded', function() {
videoSwitch();
});
编辑:在Duskwuff的链接之后,我通过创建一个新的.js文件来实现它。我把标签放在HTML的头部,将videoSwitch()移动到新的.js文件中,并添加了
public class MainActivity extends Activity {
private static final String TAG = "MainActivity";
ProductDatabase.ProductDatabaseHelper controller = new ProductDatabase.ProductDatabaseHelper(this);
EditText mBarcodeEdit;
EditText mFormatEdit;
EditText mTitleEdit;
EditText mPriceEdit;
private static final int ZBAR_SCANNER_REQUEST = 0;
private static final int ZBAR_QR_SCANNER_REQUEST = 1;
private static final ProductData mProductData = new ProductData();
Button mScanButton;
Button mAddButton;
Button mSelectButton;
Button mExportButton;
Button btnimport;
ProductDatabase mProductDb;
ListView ls;
TextView infotext;
File file = null;
// DatabaseHelper dbhelper = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ls = (ListView) findViewById(R.id.placeslist);
mBarcodeEdit = (EditText) findViewById(R.id.barcodeEdit);
mFormatEdit = (EditText) findViewById(R.id.codeFormatEdit);
mTitleEdit = (EditText) findViewById(R.id.titleEdit);
mPriceEdit = (EditText) findViewById(R.id.priceEdit);
mScanButton = (Button) findViewById(R.id.scan_btn);
mAddButton = (Button) findViewById(R.id.addButton);
mSelectButton = (Button) findViewById(R.id.selelctButton);
mProductDb = new ProductDatabase(this); // not yet shown
infotext = (TextView) findViewById(R.id.txtresulttext);
mExportButton = (Button) findViewById(R.id.exportbtn);
mSelectButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(MainActivity.this, product_list.class);
startActivity(i);
}
});
mAddButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String barcode = mBarcodeEdit.getText().toString();
String format = mFormatEdit.getText().toString();
String title = mTitleEdit.getText().toString();
String price = mPriceEdit.getText().toString();
String errors = validateFields(barcode, format, title, price);
if (errors.length() > 0) {
showInfoDialog(MainActivity.this, "Please fix errors", errors);
} else {
mProductData.barcode = barcode;
mProductData.format = format;
mProductData.title = title;
mProductData.price = new BigDecimal(price);
mProductDb.insert(mProductData);
showInfoDialog(MainActivity.this, "Success", "Product saved successfully");
resetForm();
}
}
});
mExportButton.setOnClickListener(new View.OnClickListener() {
SQLiteDatabase sqldb = controller.getReadableDatabase(); //My Database class
Cursor c =null;
@Override
public void onClick(View view) { //main code begins here
try {
c = sqldb.rawQuery("select * from spot_pay.db", null);
int rowcount = 0;
int colcount = 0;
File sdCardDir = Environment.getExternalStorageDirectory();
String filename = "MyBackUp.csv";
// the name of the file to export with
File saveFile = new File(sdCardDir, filename);
FileWriter fw = new FileWriter(saveFile);
BufferedWriter bw = new BufferedWriter(fw);
rowcount = c.getCount();
colcount = c.getColumnCount();
if (rowcount > 0) {
c.moveToFirst();
for (int i = 0; i < colcount; i++) {
if (i != colcount - 1) {
bw.write(c.getColumnName(i) + ",");
} else {
bw.write(c.getColumnName(i));
}
}
bw.newLine();
for (int i = 0; i < rowcount; i++) {
c.moveToPosition(i);
for (int j = 0; j < colcount; j++) {
if (j != colcount - 1)
bw.write(c.getString(j) + ",");
else
bw.write(c.getString(j));
}
bw.newLine();
}
bw.flush();
infotext.setText("Exported Successfully.");
}
} catch (Exception ex) {
if (sqldb.isOpen()) {
sqldb.close();
infotext.setText(ex.getMessage().toString());
}
} finally {
}
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
private void showInfoDialog(Context context, String title, String information) {
new AlertDialog.Builder(context)
.setMessage(information)
.setTitle(title)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
}).show();
}
private void resetForm() {
// TODO Auto-generated method stub
mBarcodeEdit.getText().clear();
mFormatEdit.getText().clear();
mTitleEdit.getText().clear();
mPriceEdit.getText().clear();
}
public void launchScanner(View v) {
if (isCameraAvailable()) {
Intent intent = new Intent(this, ZBarScannerActivity.class);
startActivityForResult(intent, ZBAR_SCANNER_REQUEST);
} else {
Toast.makeText(this, "Rear Facing Camera Unavailable", Toast.LENGTH_SHORT).show();
}
}
public void launchQRScanner(View v) {
if (isCameraAvailable()) {
Intent intent = new Intent(this, ZBarScannerActivity.class);
intent.putExtra(ZBarConstants.SCAN_MODES, new int[]{Symbol.QRCODE});
startActivityForResult(intent, ZBAR_SCANNER_REQUEST);
} else {
Toast.makeText(this, "Rear Facing Camera Unavailable", Toast.LENGTH_SHORT).show();
}
}
public boolean isCameraAvailable() {
PackageManager pm = getPackageManager();
return pm.hasSystemFeature(PackageManager.FEATURE_CAMERA);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case ZBAR_SCANNER_REQUEST:
case ZBAR_QR_SCANNER_REQUEST:
if (resultCode == RESULT_OK) {
mBarcodeEdit.setText(data.getStringExtra(ZBarConstants.SCAN_RESULT));
// Toast.makeText(this, "Scan Result = " + data.getStringExtra(ZBarConstants.SCAN_RESULT), Toast.LENGTH_SHORT).show();
} else if (resultCode == RESULT_CANCELED && data != null) {
String error = data.getStringExtra(ZBarConstants.ERROR_INFO);
if (!TextUtils.isEmpty(error)) {
Toast.makeText(this, error, Toast.LENGTH_SHORT).show();
}
}
break;
}
}
private static String validateFields(String barcode, String format,
String title, String price) {
StringBuilder errors = new StringBuilder();
if (barcode.matches("^\\s*$")) {
errors.append("Barcode required\n");
}
if (format.matches("^\\s*$")) {
errors.append("Format required\n");
}
if (title.matches("^\\s*$")) {
errors.append("Title required\n");
}
if (!price.matches("^-?\\d+(.\\d+)?$")) {
errors.append("Need numeric price\n");
}
return errors.toString();
}
}
答案 0 :(得分:0)
首先:您无法使用window.open
,因为您的扩展程序脚本不会在当前页面的上下文中运行。它在一个永远不可见的单独的后台页面中运行,并且无法访问某些需要&#34;真实&#34;工作的窗口。
无论如何,您对chrome.tabs.executeScript
的调用并没有做任何事情,因为在创建标签后,在页面实际加载之前,它会立即运行。由于该页面尚未加载,document.getElementById("Video1")
不会返回任何内容。
内联脚本由于其他原因而失败。属于扩展程序的页面受a strict security policy的约束,但不允许使用内联脚本。您需要将此脚本移动到单独的Javascript文件中,并使用<script src=…></script>
标记将其加载到HTML文件中。
答案 1 :(得分:-1)
这是Chrome的插件,对Firefox无用。如果你想在Firefox中运行,你必须学习如何开发Firefox的插件