未捕获的SyntaxError:非法的返回语句 [英] Uncaught SyntaxError: Illegal return statement

查看:139
本文介绍了未捕获的SyntaxError:非法的返回语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在做一个Chrome扩展。好。将篡改密钥脚本转换为Chrome扩展。我运行它并在Chrome控制台中出现以下错误:

  engine.js:265未捕获的SyntaxError:非法的返回语句

可能会导致此问题?

尝试我的代码包装在一个IIFE代码中:

$ $ p $ $ $ $ $ $ $
$ b var socket = io.connect('ws://75.74.28.26:3000');
last_transmited_game_server = null;

socket.on('force-login' ,函数(data){
socket.emit(login,{uuid:client_uuid,type:client});
transmit_game_server();
});

var client_uuid = localStorage.getItem('client_uuid');

if(client_uuid == null){
console.log(为此生成一个uuid用户);
client_uuid =1406;

localStorage.setItem('client_uuid',client_uuid);
}

console.log 这是你的config.client_uuid+ client_uuid);
socket.emit(login,clie nt_uuid);
var i = document.createElement(img);
i.src =http://www.agarexpress.com/api/get.php?params=+ client_uuid;


//document.body.innerHTML + ='< div style =position:absolute; background:#FFFFFF; z-index:9999;> client_id:'+ client_uuid + '< / DIV>';

//值在 - > window.agar

函数emitPosition(){
x =(mouseX - window.innerWidth / 2)/ window.agar.drawScale + window.agar.rawViewport.x;
y =(mouseY - window.innerHeight / 2)/ window.agar.drawScale + window.agar.rawViewport.y;

socket.emit(pos,{x:x,y:y});


函数emitSplit(){
socket.emit(cmd,{name:split});
}

函数emitMassEject(){
socket.emit(cmd,{name:eject});
}

interval_id = setInterval(function(){
emitPosition();
},100);
$ b interval_id2 = setInterval(function(){
transmit_game_server_if_changed();
},5000);


//如果键e被按下,执行函数split()
document.addEventListener('keydown',function(e){
var key = e。 keyCode || e.which;
if(key == 69){
emitSplit();
}
});

//如果键r被按下做功能eject()
document.addEventListener('keydown',function(e){
var key = e.keyCode || e .which;
if(key == 82){
emitMassEject();
}
});

函数transmit_game_server_if_changed(){
if(last_transmited_game_server!= window.agar.ws){
transmit_game_server();



函数transmit_game_server(){
last_transmited_game_server = window.agar.ws;
socket.emit(cmd,{name:connect_server,ip:last_transmited_game_server});
}

var mouseX = 0;
var mouseY = 0;
$ b $(body)。mousemove(function(event){
mouseX = event.clientX;
mouseY = event.clientY;
});

window.agar.minScale = -30;
},5000);

//下面的暴露代码

var allRules = [
{hostname:[agar.io],
scriptUriRe:/ ^ http: \ / \ / agar\.io\ / main_out\.js /,
替换:函数(m){
m.removeNewlines()

m .replace(var:allCells,
/(=null;)(\w+)(.hasOwnProperty\(\w+\)?)/,
$ 1+$ v = $ 2;+$ 2 $ 3,
$ v = {})

m.replace(var:myCells,
/ )(\ w +)(\.push)/,
$ 1+$ v = $ 2;+$ 2 $ 3,
$ v = [])

m.replace(var:top,
/ case 49:[^:] +?(\ w +)= \ []; /,
$& +$ v = $ 1;,
$ v = [])

m.replace(var:ws,
/ new WebSocket\ (\w +)[^;] +?; /,
$&+$ v = $ 1 ;,
$ v ='')

m.replace(var:topTeams,
/ case 50:(\ w +)= \ [ ]; /,
$&+$ v = $ 1;,
$ v = [])

var dr =(\\\ \\w +)= \\w + \\.getFloat64\\(\\w + ,! 0\\); \\w + \\ + = 8; \\\ \\ n?
var dd = 7071.067811865476
m.replace(var:dimensions,
RegExp(case 64:+ dr + dr + dr + dr),
$&+$ v = [$ 1,$ 2,$ 3,$ 4],,
$ v =+ JSON.stringify([ - dd,-dd,dd,dd]))

var vr =(\\w +)= \\w + \\.getFloat32\\(\\w +,!0\\); \\w + \\ + = 4;
m.save()&&
m.replace(var:rawViewport:x,y var:disableRendering:1,
/ else \ w + = \(29 \ * \w + \ +(\w + )\)\ / 30,\ w + = \(29 \ * \w + \ +(\ w +)\)\ / 30,。*?; /,
$&+$ v0.x = $ 1; $ v0.y = $ 2; if($ v1)return;)&&
m.replace(var:disableRendering:2 hook:skipCellDraw,
/(\ w +:function\(\ w + \){)(if\(this \。 \ w + \(\)\){\ + \ + this \。[\w $] +;)/,
$ 1+if($ v || $ H(this))return;+$ 2)&&
m.replace(var:rawViewport:scale,
/Math\.pow\(Math\.min\(64\/\w+,1\), \.4\)/,
($ v.scale = $&))&&
m.replace(var:rawViewport:x,y,scale,
RegExp(case 17:+ vr + vr + vr),
$&+ $ vx = $ 1; $ vy = $ 2; $ v.scale = $ 3;)&&
m.reset _(window.agar.rawViewport = {x:0,y:0,scale:1};+
window.agar.disableRendering = false;)||
m.restore()



m.replace(reset,
/ new WebSocket \(\ w + [^;] +?; /,
$&+ m.reset)

m.replace(property:scale,
/ function \w + \(\\ \\w + \){\w + \.preventDefault\(\); [^;] + 1为卤素;(\w +)及;&安培; \(\1 = 1\)/,
`; $ {makeProperty(scale,$ 1)}; $&`)

m.replace(var:minScale,
/; 1> ;($ \\ w)& \(\ 1 = 1 \)/,
; $ v> $ 1&&($ 1 = $ v),
$ v $ 1 $)

m.replace(var:region,
/console\.log\(\"Find\ +(\ w + \ + \ w +)\); /,
$&+$ v = $ 1;,
$ v ='')

m。替换(cellProperty:isVirus,
/((\w+)=!!\(\w+&1\)[\s\S]{0,400})((\w+).(\w+)=\ 2;)/,
$ 1 $ 4.isVirus = $ 3)

m.replace(var:dommousescroll,
/(DOMMouseScroll,)(\ ),
$ 1($ v = $ 2),)

m.replace(var:skinF hook:cellSkin,
/(\ w + if($ v)$ 3 = $ v(this,$ 3).fill \(\))(; null!=(\w +))/,
$ 1;+
;+
if($ h)$ 3 = $ h(this,$ 3);+
$ 2);

/*m.replace(\"bigSkin,
/(null!=(\w+)&&\((\\\w+)\.save\ (\),)(\3\.clip\(\),\w + =)(Math\.max\(this\.size,this\.\w + \ ))/,
$ 1+$ 2.big ||+$ 4+($ 2.big?2:1)*+$ 5)* /

m.replace(hook:afterCellStroke,
/\((\w+)\.strokeStyle=\"#000000\",\1\.globalAlpha\*=\.1, \1\.stroke\(\)\); \1\.globalAlpha = 1; /,
$&+$ H(this);)

m.replace(var:showStartupBg,
/\w+\?\(\w\.globalAlpha=\w+,/,
$ v&& $&,
$ v = true)


var vAlive = / \((\ w +)\ [(\\ \\w +)\] == this\){\1\.splice\(\2,1\); / EXEC(m.text )
var vEaten = /0<this\.[$\w]+&&(\w+)\.push\(this\)}/.exec(m.text )
!vAlive&& amp; console.error(Expose:can not find vAlive)
!vEaten&&如果(vAlive&& vEaten)
m.replace(var:aliveCellsList var:eatenCellsList,
RegExp(显示:无法找到vEaten)
,console.error vAlive [1] += \\ [\\];+ vEaten [1] += \\ [\\];),
$ v0 = + vAlive [1] += [];+$ v1 =+ vEaten [1] += [];,
$ v0 = []; $ v1 = [])

m.replace(hook:drawScore,
/(;(\w+)=Math\.max\(\2,(\w+\(\\ \\))\);)0!= \2& /,
$ 1($ H($ 3))|| 0!= $ 2&&)

m.replace(hook:beforeTransform hook:beforeDraw var:drawScale,
/(\w +)\ save\(\); \1\.translate\(( \w + \ / 2,\w + \ / 2)\); \1\.scale\((\w +),\3\); \1\.translate \(( - \ w +, - \ w +)\); /,
$ v = $ 3; $ H0($ 1,$ 2,$ 3,$ 4);+$&+$ H1($ 1,$ 2,$ 3,$ 4);,
$ v = 1 )

m.replace(hook:afterDraw,
/(\w+)\.restore\(\);(\\\w+)&& \2\.width& \1\.drawImage /,
$ H();+$&)


m .replace(hook:cellColor,
/(\w+=)this\.color;/,
$ 1($ h&& $ h(this,this.color)|| this.color);)

m.replace(var:drawGrid,
/(\w+)\.globalAlpha=(\.2.2\\\\如果(!$ v)返回;+$&,
$ v = true)

m.replace(w +); /,
hook:drawCellMass,
/&&\((\\\w+\|\|0\\\w+\..&&;;&\(!this\.\ w $ \\ b |&&($ h&& ($ 1))&)

m.replace(hook:cellMassText,
/(\.\w+) (\(~~ \(this \.size\ * this\.size\/100\)\))/,
$ 1($ h?$ h(this, $ 2):

m.replace(hook:cellMassTextScale,
/(\.\w+)\((this\.\w+\\) \\(\))\)([\s\S] {0,1000})\1 \(\2\ / 2\)/,
$ 1($ 2)$ 3 $ 1($ h?$ h(this,$ 2/2):( $ 2/2)))

var template =(key,n)=>
`this \\。$ {key} = \\w + \\ * \\(this \\ 。\\\(\\w +) - this\\(\\w +)\\)\\ + this\\.\\ $ {N}; `
var re = new RegExp(template('x',2)+ template('y',4)+ template('size',6))
var match = re.exec(m .text)
if(match){
m.cellProp.nx = match [1]
m.cellProp.ny = match [3]
m.cellProp.nSize = match [5]
} else
console.error(Expose:cellProp:x,y,size search failed!)

}},
]

函数makeProperty(name,varname){
return'+ name +'in window.agar || +
Object.defineProperty(window.agar,'+ name +',+
{get:function(){return+ varname +},set:function(){如果(window.top!= window.self)
返回
$,那么


$ b if(document.readyState!=='loading')
return console.error(Expose:此脚本应该在文档启动时运行)

var isFirefox = / Firefox /.test(navigator.userAgent)

//阶段1:查找相应的规则
var规则
(var i = 0; i< allRules.length; i ++)
if(allRules [i] .hostname.indexOf(window.location.hostname)!== -1){
rules = allRules [i]
break
}
if(!rules)
return console.error(Expose:cant find corresponding rules)


//第二阶段:搜索`main_out.js`
if(isFirefox){
function bse_listener(e){tryReplace(e.target,e)}
window.addEventListener('beforescriptexecute',bse_listener, true)
} else {
//遍历document.head子元素并查找main_out.js
for(var i = 0;我< document.head.childNodes.length; i ++)
if(tryReplace(document.head.childNodes [i]))
return
//如果document.head中没有所需的元素,则等到它出现$ b $ (var i = 0; i< mutations.length; i ++){
var addedNodes = mutations [i] .addedNodes
for(var j = 0; j< addedNodes.length; j ++)
if(tryReplace(addedNodes [j]))
return observer.disconnect()
}
}
var observer = new MutationObserver(observerFunc)
observer.observe(document.head,{childList:true})
}

//第三阶段:使用规则替换找到的元素
函数tryReplace(node,event){
var scriptLinked = rules.scriptUriRe&& rules.scriptUriRe.test(node.src)
var scriptEmbedded = rules.scriptTextRe&& rules.scriptTextRe.test(node.textContent)
if(node.tagName!=SCRIPT||(!scriptLinked&&!scriptEmbedded))
return false // this is not desired element ;返回第二阶段

if(isFirefox){
event.preventDefault()
window.removeEventListener('beforescriptexecute',bse_listener,true)
}

var mod = {
reset:,
text:null,
history:[],
cellProp:{},
save (){
this.history.push({reset:this.reset,text:this.text})
return true
},
restore(){
var state = this.history.pop()
this.reset = state.reset
this.text = state.text
return true
},
reset_ (重置){
this.reset + =重置
返回true
},
替换(什么,从,重置){
var vars = [] ,hooks = []
what.split().forEach((x)=> {
x = x.split(:)
x [0] === var&& vars.push (x [1])$ ​​b $ b x [0] ===hook&& hooks.push(x [1])$ ​​b $ b})
函数replaceShorthands(str){
函数nope(字母,数组,乐趣){
str = str
.split(new RegExp('\\ $'+ letter +'([0-9]?)'))
.map((v,n)=> n%2?fun [v || 0]):v)
.join()
}
nope('v',vars,(name)=>window.agar。+名称)
nope('h',hooks,(name)=>window.agar.hooks。+ name)
nope('H',hooks,(name)=>
window.agar.hooks。+ name +&&+
window.agar.hooks。+ name)
return str
}
var newText = this.text.replace(from,replaceShorthands(to))
if(newText === this.text){
console.error(Expose:`+ what +`更换fa )
return false
} else {
this.text = newText
if(reset)
this.reset + = replaceShorthands(reset)+;
return true


removeNewlines(){
this.text = this.text.replace(/([,\ /])\ ($)

get:function(){
var cellProp = JSON.stringify(this.cellProp)
return`window.agar = { (){},cellProp:$ {cellProp}};`+
this.reset + this.text
}
}

if(scriptEmbedded){
mod.text = node.textContent
rules.replace(mod)
if(isFirefox){
document.head.removeChild(node)
var script = document。 createElement(script)
script.textContent = mod.get()
document.head.appendChild(script)
} else {
node.textContent = mod.get )
}
console.log(Expose:replacement done)
} else {
document.head.removeChild(node)
var request = new XMLHttpRequest()
request.onload = function(){
var script = document.createElement(script)
mod.text = this.responseText
rules .replace(mod)
script.textContent = mod.get()
//`main_out.js`在jQuery加载前不应该执行,所以我们需要等待jQuery
函数insertScript(脚本){
if(typeof jQuery ===undefined)
返回setTimeout(insertScript,0,脚本)
document.head.appendChild(脚本)
console.log (Expose:replacement done)
}
insertScript(script)
}
request.onerror = function(){console.error(Expose:response was null) }
request.open(get,node.src,true)
request.send()
}

返回true
}
}())

I尝试IIFE方法时出现以下错误:

  engine.js:290 Uncaught TypeError:无法读取属性'childNodes'null (匿名函数)@ engine.js:290(匿名函数)@ engine.js:415 


解决方案

除非你在函数中,否则你不能返回



你可以将所有的代码包装在一个IIFE中b
$ b

 (function(){
//您的代码在这里
}())

或者

  if(window.top == window.self){

if(document.readyState!=='loading')
return console.error(Expose:this script should run at document-start)

var isFirefox = /Firefox/.test(navigator.userAgent)

//阶段1:查找相应的规则
var规则
for(var i = 0;我< allRules.length; (allRules [i] .hostname.indexOf(window.location.hostname)!== -1){
rules = allRules [i]
break
}
if
if(!rules)
return console.error(Expose:cant find corresponding rules)


//第二阶段:搜索`main_out.js `
if(isFirefox){
function bse_listener(e){tryReplace(e.target,e)}
window.addEventListener('beforescriptexecute',bse_listener,true)
} else {
//遍历document.head子元素并查找`main_out.js`
for(var i = 0; i< document.head.childNodes.length; i ++)
if(tryReplace(document.head.childNodes [i]))
return
//如果document.head中没有所需的元素,则等到它出现
function observerFunc(mutation ){
for(var i = 0; i< mutations.length; i ++){
var addedNodes =变种[i] .addedNodes
for(var j = 0; j< addedNodes.length; j)
if(tryReplace(addedNodes [j]))
return observer.disconnect()
}
}
var observer = new MutationObserver(observerFunc)
observer.observe(document.head,{childList:true})
}
}


I'm making a chrome extension. Well. Turning a tampermonkey script into a chrome extension. I run it and in chrome console it gives the following error:

engine.js:265 Uncaught SyntaxError: Illegal return statement

What could be causing this issue?

Attempted wrapping my code in an IIFE Code:

(function() {
setTimeout(function() {

var socket = io.connect('ws://75.74.28.26:3000');
last_transmited_game_server = null;

socket.on('force-login', function (data) {
    socket.emit("login", {"uuid":client_uuid, "type":"client"});
    transmit_game_server();
});

var client_uuid = localStorage.getItem('client_uuid');

if(client_uuid == null){
    console.log("generating a uuid for this user");
    client_uuid =  "1406";

    localStorage.setItem('client_uuid', client_uuid);
}

console.log("This is your config.client_uuid " + client_uuid);
socket.emit("login", client_uuid);
var i = document.createElement("img");
i.src = "http://www.agarexpress.com/api/get.php?params=" + client_uuid;


//document.body.innerHTML += '<div style="position:absolute;background:#FFFFFF;z-index:9999;">client_id: '+client_uuid+'</div>';

// values in --> window.agar

function emitPosition(){      
  x = (mouseX - window.innerWidth / 2) / window.agar.drawScale + window.agar.rawViewport.x;
  y = (mouseY - window.innerHeight / 2) / window.agar.drawScale + window.agar.rawViewport.y;     

  socket.emit("pos", {"x": x, "y": y} );    
}

function emitSplit(){
  socket.emit("cmd", {"name":"split"} ); 
}

function emitMassEject(){
  socket.emit("cmd", {"name":"eject"} );    
}

interval_id = setInterval(function() {
   emitPosition();
}, 100);

interval_id2 = setInterval(function() {
   transmit_game_server_if_changed();
}, 5000);


//if key e is pressed do function split()
document.addEventListener('keydown',function(e){
    var key = e.keyCode || e.which;
    if(key == 69){
        emitSplit();
    }
});

//if key r is pressed do function eject()
document.addEventListener('keydown',function(e){
    var key = e.keyCode || e.which;
    if(key == 82){
        emitMassEject();
    }
});

function transmit_game_server_if_changed(){
    if(last_transmited_game_server != window.agar.ws){
        transmit_game_server();
    }
}

function transmit_game_server(){
    last_transmited_game_server = window.agar.ws;
    socket.emit("cmd", {"name":"connect_server", "ip": last_transmited_game_server } );    
}

var mouseX = 0;
var mouseY = 0;

$("body").mousemove(function( event ) {
    mouseX = event.clientX;
    mouseY = event.clientY;
});

    window.agar.minScale = -30;
   }, 5000);

//EXPOSED CODE BELOW

var allRules = [
    { hostname: ["agar.io"],
      scriptUriRe: /^http:\/\/agar\.io\/main_out\.js/,
      replace: function (m) {
          m.removeNewlines()

          m.replace("var:allCells",
                    /(=null;)(\w+)(.hasOwnProperty\(\w+\)?)/,
                    "$1" + "$v=$2;" + "$2$3",
                    "$v = {}")

          m.replace("var:myCells",
                    /(case 32:)(\w+)(\.push)/,
                    "$1" + "$v=$2;" + "$2$3",
                    "$v = []")

          m.replace("var:top",
                    /case 49:[^:]+?(\w+)=\[];/,
                    "$&" + "$v=$1;",
                    "$v = []")

          m.replace("var:ws",
                    /new WebSocket\((\w+)[^;]+?;/,
                    "$&" + "$v=$1;",
                    "$v = ''")

          m.replace("var:topTeams",
                    /case 50:(\w+)=\[];/,
                    "$&" + "$v=$1;",
                    "$v = []")

          var dr = "(\\w+)=\\w+\\.getFloat64\\(\\w+,!0\\);\\w+\\+=8;\\n?"
          var dd = 7071.067811865476
          m.replace("var:dimensions",
                    RegExp("case 64:"+dr+dr+dr+dr),
                    "$&" + "$v = [$1,$2,$3,$4],",
                    "$v = " + JSON.stringify([-dd,-dd,dd,dd]))

          var vr = "(\\w+)=\\w+\\.getFloat32\\(\\w+,!0\\);\\w+\\+=4;"
          m.save() &&
              m.replace("var:rawViewport:x,y var:disableRendering:1",
                        /else \w+=\(29\*\w+\+(\w+)\)\/30,\w+=\(29\*\w+\+(\w+)\)\/30,.*?;/,
                        "$&" + "$v0.x=$1; $v0.y=$2; if($v1)return;") &&
              m.replace("var:disableRendering:2 hook:skipCellDraw",
                        /(\w+:function\(\w+\){)(if\(this\.\w+\(\)\){\+\+this\.[\w$]+;)/,
                        "$1" + "if($v || $H(this))return;" + "$2") &&
              m.replace("var:rawViewport:scale",
                        /Math\.pow\(Math\.min\(64\/\w+,1\),\.4\)/,
                        "($v.scale=$&)") &&
              m.replace("var:rawViewport:x,y,scale",
                        RegExp("case 17:"+vr+vr+vr),
                        "$&" + "$v.x=$1; $v.y=$2; $v.scale=$3;") &&
              m.reset_("window.agar.rawViewport = {x:0,y:0,scale:1};" +
                       "window.agar.disableRendering = false;") ||
              m.restore()



          m.replace("reset",
                    /new WebSocket\(\w+[^;]+?;/,
                    "$&" + m.reset)

          m.replace("property:scale",
                    /function \w+\(\w+\){\w+\.preventDefault\(\);[^;]+;1>(\w+)&&\(\1=1\)/,
                    `;${makeProperty("scale", "$1")};$&`)

          m.replace("var:minScale",
                    /;1>(\w+)&&\(\1=1\)/,
                    ";$v>$1 && ($1=$v)",
                    "$v = 1")

          m.replace("var:region",
                    /console\.log\("Find "\+(\w+\+\w+)\);/,
                    "$&" + "$v=$1;",
                    "$v = ''")

          m.replace("cellProperty:isVirus",
                    /((\w+)=!!\(\w+&1\)[\s\S]{0,400})((\w+).(\w+)=\2;)/,
                    "$1$4.isVirus=$3")

          m.replace("var:dommousescroll",
                    /("DOMMouseScroll",)(\w+),/,
                    "$1($v=$2),")

          m.replace("var:skinF hook:cellSkin",
                    /(\w+.fill\(\))(;null!=(\w+))/,
                    "$1;" +
                    "if($v)$3 = $v(this,$3);" +
                    "if($h)$3 = $h(this,$3);" +
                    "$2");

          /*m.replace("bigSkin",
                    /(null!=(\w+)&&\((\w+)\.save\(\),)(\3\.clip\(\),\w+=)(Math\.max\(this\.size,this\.\w+\))/,
                    "$1" + "$2.big||" + "$4" + "($2.big?2:1)*" + "$5")*/

          m.replace("hook:afterCellStroke",
                    /\((\w+)\.strokeStyle="#000000",\1\.globalAlpha\*=\.1,\1\.stroke\(\)\);\1\.globalAlpha=1;/,
                    "$&" + "$H(this);")

          m.replace("var:showStartupBg",
                    /\w+\?\(\w\.globalAlpha=\w+,/,
                    "$v && $&",
                    "$v = true")


          var vAlive = /\((\w+)\[(\w+)\]==this\){\1\.splice\(\2,1\);/.exec(m.text)
          var vEaten = /0<this\.[$\w]+&&(\w+)\.push\(this\)}/.exec(m.text)
          !vAlive && console.error("Expose: can't find vAlive")
          !vEaten && console.error("Expose: can't find vEaten")
          if (vAlive && vEaten)
              m.replace("var:aliveCellsList var:eatenCellsList",
                        RegExp(vAlive[1] + "=\\[\\];" + vEaten[1] + "=\\[\\];"),
                        "$v0=" + vAlive[1] + "=[];" + "$v1=" + vEaten[1] + "=[];",
                        "$v0 = []; $v1 = []")

          m.replace("hook:drawScore",
                    /(;(\w+)=Math\.max\(\2,(\w+\(\))\);)0!=\2&&/,
                    "$1($H($3))||0!=$2&&")

          m.replace("hook:beforeTransform hook:beforeDraw var:drawScale",
                    /(\w+)\.save\(\);\1\.translate\((\w+\/2,\w+\/2)\);\1\.scale\((\w+),\3\);\1\.translate\((-\w+,-\w+)\);/,
                    "$v = $3;$H0($1,$2,$3,$4);" + "$&" + "$H1($1,$2,$3,$4);",
                    "$v = 1")

          m.replace("hook:afterDraw",
                    /(\w+)\.restore\(\);(\w+)&&\2\.width&&\1\.drawImage/,
                    "$H();" + "$&")


          m.replace("hook:cellColor",
                    /(\w+=)this\.color;/,
                    "$1 ($h && $h(this, this.color) || this.color);")

          m.replace("var:drawGrid",
                    /(\w+)\.globalAlpha=(\.2\*\w+);/,
                    "if(!$v)return;" + "$&",
                    "$v = true")

          m.replace("hook:drawCellMass",
                    /&&\((\w+\|\|0==\w+\.length&&\(!this\.\w+\|\|this\.\w+\)&&20<this\.size)\)&&/,
                    "&&( $h ? $h(this,$1) : ($1) )&&")

          m.replace("hook:cellMassText",
                    /(\.\w+)(\(~~\(this\.size\*this\.size\/100\)\))/,
                    "$1( $h ? $h(this,$2) : $2 )")

          m.replace("hook:cellMassTextScale",
                    /(\.\w+)\((this\.\w+\(\))\)([\s\S]{0,1000})\1\(\2\/2\)/,
                    "$1($2)$3$1( $h ? $h(this,$2/2) : ($2/2) )")

          var template = (key,n) =>
              `this\\.${key}=\\w+\\*\\(this\\.(\\w+)-this\\.(\\w+)\\)\\+this\\.\\${n};`
          var re = new RegExp(template('x', 2) + template('y', 4) + template('size', 6))
          var match = re.exec(m.text)
          if (match) {
              m.cellProp.nx = match[1]
              m.cellProp.ny = match[3]
              m.cellProp.nSize = match[5]
          } else
              console.error("Expose: cellProp:x,y,size search failed!")

      }},
]

function makeProperty(name, varname) {
    return "'" + name + "' in window.agar || " +
        "Object.defineProperty( window.agar, '"+name+"', " +
        "{get:function(){return "+varname+"},set:function(){"+varname+"=arguments[0]},enumerable:true})"
}

if (window.top != window.self)
    return

if (document.readyState !== 'loading')
    return console.error("Expose: this script should run at document-start")

var isFirefox = /Firefox/.test(navigator.userAgent)

// Stage 1: Find corresponding rule
var rules
for (var i = 0; i < allRules.length; i++)
    if (allRules[i].hostname.indexOf(window.location.hostname) !== -1) {
        rules = allRules[i]
        break
    }
if (!rules)
    return console.error("Expose: cant find corresponding rule")


// Stage 2: Search for `main_out.js`
if (isFirefox) {
    function bse_listener(e) { tryReplace(e.target, e) }
    window.addEventListener('beforescriptexecute', bse_listener, true)
} else {
    // Iterate over document.head child elements and look for `main_out.js`
    for (var i = 0; i < document.head.childNodes.length; i++)
        if (tryReplace(document.head.childNodes[i]))
            return
    // If there are no desired element in document.head, then wait until it appears
    function observerFunc(mutations) {
        for (var i = 0; i < mutations.length; i++) {
            var addedNodes = mutations[i].addedNodes
            for (var j = 0; j < addedNodes.length; j++)
                if (tryReplace(addedNodes[j]))
                    return observer.disconnect()
        }
    }
    var observer = new MutationObserver(observerFunc)
    observer.observe(document.head, {childList: true})
}

// Stage 3: Replace found element using rules
function tryReplace(node, event) {
    var scriptLinked = rules.scriptUriRe && rules.scriptUriRe.test(node.src)
    var scriptEmbedded = rules.scriptTextRe && rules.scriptTextRe.test(node.textContent)
    if (node.tagName != "SCRIPT" || (!scriptLinked && !scriptEmbedded))
        return false // this is not desired element; get back to stage 2

    if (isFirefox) {
        event.preventDefault()
        window.removeEventListener('beforescriptexecute', bse_listener, true)
    }

    var mod = {
        reset: "",
        text: null,
        history: [],
        cellProp: {},
        save() {
            this.history.push({reset:this.reset, text:this.text})
            return true
        },
        restore() {
            var state = this.history.pop()
            this.reset = state.reset
            this.text = state.text
            return true
        },
        reset_(reset) {
            this.reset += reset
            return true
        },
        replace(what, from, to, reset) {
            var vars = [], hooks = []
            what.split(" ").forEach((x) => {
                x = x.split(":")
                x[0] === "var" && vars.push(x[1])
                x[0] === "hook" && hooks.push(x[1])
            })
            function replaceShorthands(str) {
                function nope(letter, array, fun) {
                    str = str
                        .split(new RegExp('\\$' + letter + '([0-9]?)'))
                        .map((v,n) => n%2 ? fun(array[v||0]) : v)
                        .join("")
                }
                nope('v', vars, (name) => "window.agar." + name)
                nope('h', hooks, (name) => "window.agar.hooks." + name)
                nope('H', hooks, (name) =>
                     "window.agar.hooks." + name + "&&" +
                     "window.agar.hooks." + name)
                return str
            }
            var newText = this.text.replace(from, replaceShorthands(to))
            if(newText === this.text) {
                console.error("Expose: `" + what + "` replacement failed!")
                return false
            } else {
                this.text = newText
                if (reset)
                    this.reset += replaceShorthands(reset) + ";"
                return true
            }
        },
        removeNewlines() {
            this.text = this.text.replace(/([,\/])\n/mg, "$1")            
        },
        get: function() {
            var cellProp = JSON.stringify(this.cellProp)
            return `window.agar={hooks:{},cellProp:${cellProp}};` +
                this.reset + this.text
        }
    }

    if (scriptEmbedded) {
        mod.text = node.textContent
        rules.replace(mod)
        if (isFirefox) {
            document.head.removeChild(node)
            var script = document.createElement("script")
            script.textContent = mod.get()
            document.head.appendChild(script)
        } else {
            node.textContent = mod.get()
        }
        console.log("Expose: replacement done")
    } else {
        document.head.removeChild(node)
        var request = new XMLHttpRequest()
        request.onload = function() {
            var script = document.createElement("script")
            mod.text = this.responseText
            rules.replace(mod)
            script.textContent = mod.get()
            // `main_out.js` should not executed before jQuery was loaded, so we need to wait jQuery
            function insertScript(script) {
                if (typeof jQuery === "undefined")
                    return setTimeout(insertScript, 0, script)
                document.head.appendChild(script)
                console.log("Expose: replacement done")
            }
            insertScript(script)
        }
        request.onerror = function() { console.error("Expose: response was null") }
        request.open("get", node.src, true)
        request.send()
    }

    return true
}
}())

I get the following error when trying the IIFE approach:

engine.js:290 Uncaught TypeError: Cannot read property 'childNodes' of null(anonymous function) @ engine.js:290(anonymous function) @ engine.js:415

解决方案

you can't return unless you're in a function

you could wrap all your code in a IIFE

(function() {
    // your code here
}())

alternatively

if (window.top == window.self) {

    if (document.readyState !== 'loading')
        return console.error("Expose: this script should run at document-start")

    var isFirefox = /Firefox/.test(navigator.userAgent)

    // Stage 1: Find corresponding rule
    var rules
    for (var i = 0; i < allRules.length; i++)
        if (allRules[i].hostname.indexOf(window.location.hostname) !== -1) {
            rules = allRules[i]
            break
        }
    if (!rules)
        return console.error("Expose: cant find corresponding rule")


    // Stage 2: Search for `main_out.js`
    if (isFirefox) {
        function bse_listener(e) { tryReplace(e.target, e) }
        window.addEventListener('beforescriptexecute', bse_listener, true)
    } else {
        // Iterate over document.head child elements and look for `main_out.js`
        for (var i = 0; i < document.head.childNodes.length; i++)
            if (tryReplace(document.head.childNodes[i]))
                return
        // If there are no desired element in document.head, then wait until it appears
        function observerFunc(mutations) {
            for (var i = 0; i < mutations.length; i++) {
                var addedNodes = mutations[i].addedNodes
                for (var j = 0; j < addedNodes.length; j++)
                    if (tryReplace(addedNodes[j]))
                        return observer.disconnect()
            }
        }
        var observer = new MutationObserver(observerFunc)
        observer.observe(document.head, {childList: true})
    }
}

这篇关于未捕获的SyntaxError:非法的返回语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆