Javascript- if statement in Chrome keepvid script - javascript

Sorry if this is stupidly easy, but I don't even program in java.
There's keepvid.com, and they have nice script to get downloads from youtube.
Code:
javascript:(
function(){
window.open('http://keepvid.com/?url='+encodeURIComponent(location.href)+'')
}
)();
I managed to tinker with it so it takes me directly to mp3 download (adding '&mode=mp3'), but it didn't work with long url's with playlists and stuff, so I made one which cuts it off. Code:
javascript:(
function(){
var url=location.href;
url=url.substring(0, url.indexOf('&'));
window.open('http://keepvid.com/?url='+encodeURIComponent(url)+'&mode=mp3')
}
)();
Ultimately I want it to work in all cases, but if url is clean it pastes '&', I tried using IF and it works for manually written true/false, but I cant get it to work with .contains. Code:
javascript:(
function(){
var url=location.href;
if(url.contains('&')){
url=url.substring(0, url.indexOf('&'));
};
window.open(
'http://keepvid.com/?url='+encodeURIComponent(url)+'&mode=mp3'
)
}
)();

I assume you looked at the console. If you had, you would have seen an error such as "undefined is not a function", on the line where you call contains. contains is undefined because there is no method contains on strings.
There was a Firefox-specific String#contains which was changed to includes to match the ES6 spec. Some libraries may provide their own contains method on strings.
You will find includes in few if any browsers as of yet. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes. See also http://kangax.github.io/compat-table/es6/#String.prototype.contains. You can find a polyfill, which looks slightly over-engineered to me, at https://github.com/mathiasbynens/String.prototype.includes.

Instead of checking if url contains '&' as condition I set
if(url.indexOf('&')!=-1)
which states 'if index of "&" is not -1' (I guess -1 is value for not found)

Related

javascript expression expected

I am still new a Javascript tried earching and tried the development tool in Chrome, too see if I could find the problem.
Working in Intellij IDEA 13, Java, javascript and xhtml.
My problem is that I have a piece of javascript, then in IDEA when moused over, says that
Expression Expected
the javascript code looks the following
<script type="text/javascript>
function nameOfFunction(){
if(#{trendAnalysisLocationReportController.model.showTargetLine}){
this.cfg.series[this.cfg.data.length-1].pointLabels = {
show: false
};
}
}
<\script>
the method in the if sentence is a java method with a boolean return value.
the error is shown when hovering
'#{'
if Had a look at the following questions, before :
Expected Expression
boolean in an if statement
But didnt get me a solution.
what Iam I doing wrong ?
It looks as though the problem is the part that you've got within the #{...} block. Without knowing the context, it's hard to be sure, but is this something in a view/JSP page that's supposed to be replaced with a property at runtime? The if block will expect the part inside the brackets to be a boolean value, so if that's rendered to either 'true' or 'false' it would execute at runtime but would likely show the error you're seeing in your IDE as it's not actually a valid piece of JavaScript. If, on the other hand, you're expecting to be able to call your Java method/property from your JavaScript code, you're going to need to do something that requests that value from the server-side code - AJAX or similar.
Also worth noting that we can't see what this.cfg is supposed to represent. If that's your entire script block, then there's nothing that defines the cfg object within the current scope.
One last thing, you should change the <\script> end element to as it won't be understood properly by some browsers.

Object has no method 'charAt' in jQuery plugin

I am attempting to use the autoNumeric jQuery plug-in which helps with the conversion of various currencies in jQuery.
The plug-in itself works when I use it in a jsFiddle example.
$(function () {
$('.money').autoNumeric('init', {
aSign: '$',
vMin: '-999999999.99',
nBracket: '(,)'
});
});
However, as soon as I integrate it into a big, legacy project, I start receiving the above error on line 194. I know why I'm getting the error - a string is not being passed into the negativeBracket function (negativeBracket(s, nBracket, oEvent) is the signature). Instead, it seems to be a jQuery object - e.fn.init1. I'm confused on how this might be happening. I realize the community may not be able to give a direct answer, but I would love (and will accept as an answer) being pointed in the right direction as nothing has jumped out at me so far.
Update
So, have some additional info that may be of help. It still has me stumped how it's happening (unfortunately, the answers below didn't help to provide any additional insight). When I link in autoNumeric, I key it off of any text field with the class money. It does work as I am typing in the box. I can see see formatting. However, when I tab into a new box, the box I just finished typing in clears itself completely after hitting line 152 in autoNumeric with the same exact error.
#Carlos487 was correct in his answer when he said I have an object that is not a string. I instead have an object that, I believe, is a function. Here's what I'm seeing in Chrome debugger tools:
e.fn.init[1]
> 0: input#price.money required
> context: input#price.money required
length: 1
selector: ""
> __proto__: Object[0]
The "arrowed" items can be further expanded out. I don't know if this provides any more clues, but it's at least something a bit different.
The errors like
no method XXXXX in Object
are produced because you are trying to call obj.XXXX() and obj is not of the desired type, in your particular case a string.
Have you tried in another browser because older or IE can be a little troublesome. I would recomend using chrome developer tools with your legacy app to see if anything else is conflicting or producing the error
I will bet money that you are using a second library which is interfering with jQuery. It has probably overridden $ with its own function.
Try using jQuery instead of $:
jQuery(function () {
jQuery('.money').autoNumeric('init', {
aSign: '$',
vMin: '-999999999.99',
nBracket: '(,)'
});
});
It turns out that the issue was a myriad of issue compounding into the error I saw. A couple things that was happening:
The validator plug-in was wrapping the jQuery object in its own structure (hence the charAt issue).
Once I fixed that, I also learned that some homegrown code was also wiping and rewriting data into the field to provide formatting (which is what autoNumeric is also doing), so autoNumeric would bomb out because it would get a null value and attempt to format it.
There was some other random craziness that also needed cleaned up. So...issue resolved! Still more to work on, but at least this hurdle is past. Thanks all for your help.

IE Object doesn't support this property or method

This is probably the beginning of many questions to come.
I have finished building my site and I was using Firefox to view and test the site. I am now IE fixing and am stuck at the first JavaScript error which only IE seems to be throwing a hissy about.
I run the IE 8 JavaScript debugger and get this:
Object doesn't support this property or method app.js, line 1 character 1
Source of app.js (first 5 lines):
var menu = {};
menu.current = "";
menu.first = true;
menu.titleBase = "";
menu.init = function(){...
I have tested the site in a Webkit browser and it works fine in that.
What can I do to fix this? The site is pretty jQuery intensive so i have given up any hope for getting it to work in IE6 but I would appreciate it working in all the others.
UPDATE: I have upload the latest version of my site to http://www.frankychanyau.com
In IE8, your code is causing jQuery to fail on this line
$("title").text(title);
in the menu.updateTitle() function. Doing a bit of research (i.e. searching with Google), it seems that you might have to use document.title with IE.
Your issue is (probably) here:
menu.updateTitle = function(hash){
var title = menu.titleBase + ": " + $(hash).data("title");
$("title").text(title); // IE fails on setting title property
};
I can't be bothered to track down why jQuery's text() method fails here, but it does. In any case, it's much simpler to not use it. There is a title property of the document object that is the content of the document's title element. It isn't marked readonly, so to set its value you can simply assign a new one:
document.title = title;
and IE is happy with that.
It is a good idea to directly access DOM properties wherever possible and not use jQuery's equivalent methods. Property access is less troublesome and (very much) faster, usually with less code.
Well, your line 1 certainly looks straight forward enough. Assuming the error line and number is not erroneous, it makes me think there is a hidden character in the first spot of your js file that is throwing IE for a fit. Try opening the file in another text editor that may support display of normally hidden characters. Sometimes copying/pasting the source into a super-basic text-editor, like Notepad, can sometimes strip out non-displayable characters and then save it back into place directly from Notepad.

Possible cases for Javascript error: "Expected identifier, string or number"

Some users are reporting occasional JS errors on my site. The error message says "Expected identifier, string or number" and the line number is 423725915, which is just an arbitrary number and changes for each report when this occurs.
This mostly happens with IE7/ Mozilla 4.0 browsers.
I scanned my code a bunch of times and ran jslint but it didn't pick anything up - anyone know of the general type of JS problems that lead to this error message?
The cause of this type of error can often be a misplaced comma in an object or array definition:
var obj = {
id: 23,
name: "test", <--
}
If it appears at a random line, maybe it's part of an object defintion you are creating dynamically.
Using the word class as a key in a Javascript dictionary can also trigger the dreaded "Expected identifier, string or number" error because class is a reserved keyword in Internet Explorer.
BAD
{ class : 'overlay'} // ERROR: Expected identifier, string or number
GOOD
{'class': 'overlay'}
When using a reserved keyword as a key in a Javascript dictionary, enclose the key in quotes.
Hope this hint saves you a day of debugging hell.
Actually I got something like that on IE recently and it was related to JavaScript syntax "errors". I say error in quotes because it was fine everywhere but on IE. This was under IE6. The problem was related to JSON object creation and an extra comma, such as
{ one:1, two:2, three:3, }
IE6 really doesn't like that comma after 3. You might look for something like that, touchy little syntax formality issues.
Yeah, I thought the multi-million line number in my 25 line JavaScript was interesting too.
Good luck.
This is a definitive un-answer: eliminating a tempting-but-wrong answer to help others navigate toward correct answers.
It might seem like debugging would highlight the problem. However, the only browser the problem occurs in is IE, and in IE you can only debug code that was part of the original document. For dynamically added code, the debugger just shows the body element as the current instruction, and IE claims the error happened on a huge line number.
Here's a sample web page that will demonstrate this problem in IE:
<html>
<head>
<title>javascript debug test</title>
</head>
<body onload="attachScript();">
<script type="text/javascript">
function attachScript() {
var s = document.createElement("script");
s.setAttribute("type", "text/javascript");
document.body.appendChild(s);
s.text = "var a = document.getElementById('nonexistent'); alert(a.tagName);"
}
</script>
</body>
This yielded for me the following error:
Line: 54654408
Error: Object required
Just saw the bug in one of my applications, as a catch-all, remember to enclose the name of all javascript properties that are the same as keyword.
Found this bug after attending to a bug where an object such as:
var x = { class: 'myClass', function: 'myFunction'};
generated the error (class and function are keywords)
this was fixed by adding quotes
var x = { 'class': 'myClass', 'function': 'myFunction'};
I hope to save you some time
http://closure-compiler.appspot.com/home will pick this error up with an accurate reference to the actual line number in the offending script.
As noted previously, having an extra comma threw an error.
Also in IE 7.0, not having a semicolon at the end of a line caused an error. It works fine in Safari and Chrome (with no errors in console).
IE7 is much less forgiving than newer browsers, especially Chrome. I like to use JSLint to find these bugs. It will find these improperly placed commas, among other things. You will probably want to activate the option to ignore improper whitespace.
In addition to improperly placed commas, at this blog in the comments someone reported:
I've been hunting down an error that only said "Expected identifier"
only in IE (7). My research led me to this page. After some
frustration, it turned out that the problem that I used a reserved
word as a function name ("switch"). THe error wasn't clear and it
pointed to the wrong line number.
Remove the unwanted , sign in the function. you will get the solution.
Refer this
http://blog.favrik.com/2007/11/29/ie7-error-expected-identifier-string-or-number/
This error occurs when we add or missed to remove a comma at the end of array or in function code. It is necessary to observe the entire code of a web page for such error.
I got it in a Facebook app code while I was coding for a Facebook API.
<div id='fb-root'>
<script type='text/javascript' src='http://connect.facebook.net/en_US/all.js'</script>
<script type='text/javascript'>
window.fbAsyncInit = function() {
FB.init({appId:'".$appid."', status: true, cookie: true, xfbml: true});
FB.Canvas.setSize({ width: 800 , height: 860 , });
// ^ extra comma here
};
</script>
This sounds to me like a script that was pulled in with src, and loaded just halfway, causing a syntax error sine the remainder is not loaded.
IE7 has problems with arrays of objects
columns: [
{
field: "id",
header: "ID"
},
{
field: "name",
header: "Name" , /* this comma was the problem*/
},
...
Another variation of this bug: I had a function named 'continue' and since it's a reserved word it threw this error. I had to rename my function 'continueClick'
Maybe you've got an object having a method 'constructor' and try to invoke that one.
You may hit this problem while using Knockout JS. If you try setting class attribute like the example below it will fail:
<span data-bind="attr: { class: something() }"></span>
Escape the class string like this:
<span data-bind="attr: { 'class': something() }"></span>
My 2 cents.
I too had come across this issue. I found below two solutions.
1). Same as mentioned by others above, remove extra comma from JSON object.
2). Also, My JSP/HTML was having . Because of this it was triggering browser's old mode which was giving JS error for extra comma. When used it triggers browser's HTML5 mode(If supported) and it works fine even with Extra Comma just like any other browsers FF, Chrome etc.
Here is a easy technique to debug the problem:
echo out the script/code to the console.
Copy the code from the console into your IDE.
Most IDE's perform error checking on the code and highlight errors.
You should be able to see the error almost immediately in your JavaScript/HTML editor.
Had the same issue with a different configuration. This was in an angular factory definition, but I assume it could happen elsewhere as well:
angular.module("myModule").factory("myFactory", function(){
return
{
myMethod : function() // <--- error showing up here
{
// method definition
}
}
});
Fix is very exotic:
angular.module("myModule").factory("myFactory", function(){
return { // <--- notice the absence of the return line
myMethod : function()
{
// method definition
}
}
});
This can also happen in Typescript if you call a function in middle of nowhere inside a class. For example
class Dojo implements Sensei {
console.log('Hi'); // ERROR Identifier expected.
constructor(){}
}
Function calls, like console.log() must be inside functions. Not in the area where you should be declaring class fields.
Typescript for Windows issue
This works in IE, chrome, FF
export const OTP_CLOSE = { 'outcomeCode': 'OTP_CLOSE' };
This works in chrome, FF, Does not work in IE 11
export const OTP_CLOSE = { outcomeCode: 'OTP_CLOSE' };
I guess it somehow related to Windows reserved words

How do I relate a UIWebView javascript exception's sourceId to a source file?

Short question: What does an exception's "sourceID" refer to, and how can I link it to the relevant source string/file?
Longer story:
I am running Javascript code in an iPhone native app through [UIWebView stringByEvaluatingJavaScriptFromString:]. To help development, and later check user-provided code, I use the following function to safely run any code:
// Inside #implementation MyJS
- (NSString *)runJS:(NSString *)js {
// Do some escaping on 'js' to make it look like a string literal.
js = escape(js);
NSString *result =
[webView stringByEvaluatingJavaScriptFromString:
[NSString stringWithFormat:#"try { JSON.stringify(eval(\"%#\")); } except (e) { JSON.stringify(e); }", js]
];
return result;
}
If all goes well, [MyJS runJS:js] runs fine and returns a JSON string containing the result of the evaluation of the last statement in the 'js' code.
Now if bad things happen during the evaluation, I get a JSONified exception object. For example, in case of a syntax error in the 'js' code, I get something like this:
{"message":"Parse error","line":1,"sourceId":26121296}
Which is already quite useful to track problems...
However, as I run multiple strings through runJS:, I would like to be able to pinpoint which one caused the exception (because a runtime error could come from a function that was created in a previous javascript code string). This "sourceId" property looks interesting, but I cannot find what it points to. It looks like a pointer address (similar value as pointers to other objects), but it doesn't match with any of the strings I've passed to the evaluator. How can I make this link?
For bonus points: Is there any documentation available about the UIWebView-specific javascript environment, like this exception object? The Safari Web Content Guide is nice, but doesn't go into this kind of details.
Worst-case solution:
Inside each js string being evaluated, add some code that throws an exception, catches it, extracts the sourceId and somehow exposes it so that the runJS: method can keep a record of which sourceId goes with which string.
(Hopefully someone will find a better way and help bury this ugly answer!)

Categories

Resources