I need to rewrite my tampermonkey script on typescript.
What is correct way to rewrite this javascript on typescript?
if (window.top != window.self ) { return; }
Main goal is to stop executing script if it's running not in window.top.
Typescript piler write ERROR TS1108: A 'return' statement can only be used within a function body.
I need to rewrite my tampermonkey script on typescript.
What is correct way to rewrite this javascript on typescript?
if (window.top != window.self ) { return; }
Main goal is to stop executing script if it's running not in window.top.
Typescript piler write ERROR TS1108: A 'return' statement can only be used within a function body.
Share Improve this question edited Mar 2, 2015 at 13:38 thefourtheye 240k53 gold badges466 silver badges501 bronze badges asked Mar 2, 2015 at 13:37 lokhmakovlokhmakov 2071 gold badge3 silver badges6 bronze badges 2- We are missing some code here, but could your code be wrap inside a class or a function. That function could them be called from the main execution. – David Laberge Commented Mar 2, 2015 at 13:42
- This code works on javascript outside all classes and functions - it's stop execution of script and looks like: jsfiddle/4tfjvvxk – lokhmakov Commented Mar 2, 2015 at 14:04
3 Answers
Reset to default 2Here is how I would do it. Typescript transpile into Javascript, but it is not Javascript.
if(validateIfTop()){
// MAIN BODY OF YOUR USERSCRIPT GOES HERE
}
validateIfTop():boolean{
return window.top === window.self;
}
That should fix the current transpiler error. But it is possible that your code you have run fine in is current state. It's just that it does not make sense to return a value out of the main script. You might want to have a look to this question : Is it possible to stop JavaScript execution? It explain how to stop a javascript script.
I suspect that your original JS functions only conincidently, i.e. it fails silently at runtime:
I would refactor the code to be surrounded by an if
block as already suggested by David.
You cannot return outside function, but using throw Exception you can stop execution userscipts (tampermonkey) too:
if (window.top != window.self) {
throw new Error("Not on top");
}