Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/441.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript chrome扩展无法读取未定义的属性“currentScript”_Javascript_Ajax_Google Chrome_Google Chrome Extension - Fatal编程技术网

Javascript chrome扩展无法读取未定义的属性“currentScript”

Javascript chrome扩展无法读取未定义的属性“currentScript”,javascript,ajax,google-chrome,google-chrome-extension,Javascript,Ajax,Google Chrome,Google Chrome Extension,我的chrome扩展中定义了XHR请求,它从特定网站中提取一个javascript文件,并在其中执行一个函数。像这样: //This will return the remote JS file content function _curl(url) { var xhr = new XMLHttpRequest(); xhr.open('get', 'https://allow-any-origin.appspot.com/' + url, false); x

我的chrome扩展中定义了XHR请求,它从特定网站中提取一个javascript文件,并在其中执行一个函数。像这样:

//This will return the remote JS file content
function _curl(url) {
      var xhr = new XMLHttpRequest();
      xhr.open('get', 'https://allow-any-origin.appspot.com/' + url, false);
      xhr.send();
      return xhr.responseText;
}

//Here I get the JS content and execute it
var rpt = _curl('https://my-page.com/remote.js').match(/\){([^]+)}/)[1]; 
eval(rpt); //This fails with the error "Cannot read property 'currentScript' of undefined"
远程文件中定义currentScript的JS代码部分为:

...
var Uh=window.document.currentScript&&-1!=window.document.currentScript.src.indexOf("?loadGamesSDK")?"/cast_game_sender.js":"/cast_sender.js",
...

发生这种情况是因为我试图在chrome环境中执行请求吗?因为,我还尝试通过eval contents在页面内执行请求,这很有效。每当我尝试在扩展中执行同一段代码时,它就会弹出这个错误

我没有注意到脚本正在后台运行。它始终具有window.document属性。然而,由于eval失败了,我尝试用替换它,它成功了

我认为它之所以有效,是因为eval没有在jQuery.globalEval提供的全局环境中执行。再解释一下这种行为

工作代码现在看起来像:

//This will return the remote JS file content
function _curl(url) {
      var xhr = new XMLHttpRequest();
      xhr.open('get', 'https://allow-any-origin.appspot.com/' + url, false);
      xhr.send();
      return xhr.responseText;
}

//Here I get the JS content and execute it
var rpt = _curl('https://my-page.com/remote.js').match(/\){([^]+)}/)[1]; 
jQuery.globalEval(rpt); //This works now

这段代码在一般同步XHR中是可疑的?eval?,但重要的是:你想在扩展的哪个部分运行它,为什么它必须是一个远程脚本?你必须知道eval函数不能在google chrome扩展中使用。它被认为是一个不安全的调用,将抛出一个异常。@Xan它基本上是一个插件,依赖于远程javascript文件中定义的函数进行计算。如果没有JS文件中的函数,代码将毫无用处。这解释了远程脚本的用途。还有更好的办法吗?我正试图在内容脚本中运行它。@EmrysMyrooin我知道它是完全不安全的,不推荐使用。相信我,我也在努力避免它。但是我应该如何在远程JS文件中执行函数呢?还有别的办法吗?注意,远程JS是绝对必要的。我无法避免it@Emrys,这就是FUD,也可以安全地在扩展中使用eval/remote代码。