简体   繁体   English

如果语句不起作用-Chrome扩展程序

[英]If statement doesn't work - chrome extension

That is my code from my background.js: 那是我background.js的代码:

 chrome.webNavigation.onCompleted.addListener(function(o) {
   chrome.tabs.executeScript(o.tabId, {
         file: "test.js"
   });
 }, {
   url: [
     {hostContains: 'google.com'}
   ]
 });

What I want now is an if statement right where the test.js gets called. 我现在想要的是一条if语句,它在test.js被调用的地方。 Something like this: 像这样:

If a == b then execute the line 'file: "test.js"' else do nothing 如果a == b,则执行“ file:“ test.js””行,否则不执行任何操作

I tried this but it didn't work: 我试过了,但是没有用:

 chrome.webNavigation.onCompleted.addListener(function(o) {
   chrome.tabs.executeScript(o.tabId, {
         if (a == b) {
          file: "test.js"
        }

   });
 }

Anyone know what I'm doing wrong ? 有人知道我在做什么错吗? Thanks ! 谢谢 !

You can't use an if statement inside an object literal. 您不能在对象文字中使用if语句。 That's simply not valid syntax. 那根本就是无效的语法。 A possible solution would be to pass a different object based on the condition: 可能的解决方案是根据条件传递不同的对象:

 chrome.webNavigation.onCompleted.addListener(function(o) {
   chrome.tabs.executeScript(o.tabId, (a == b) ? { file: "test.js"} : {});
 }

The second parameter of the executeScript function takes an InjectDetails https://developer.chrome.com/extensions/tabs#type-InjectDetails object, you can't put an if statement in there. executeScript函数的第二个参数采用一个InjectDetails https://developer.chrome.com/extensions/tabs#type-InjectDetails对象,您不能在其中放置if语句。

You can have the if statement return an object literal, such as 您可以让if语句返回对象文字,例如

chrome.webNavigation.onCompleted.addListener(function(o) {
   chrome.tabs.executeScript(o.tabId, 
     if (a == b) return {
      file: "test.js"
     }
   );
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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