Unable to get proper Ace Editor Text in Google Chrome Extension - javascript

I am making Google Chrome Extension which gets the text from ACE Editor. But as soon as I create ACE object, formatting is lost and I am not able to get the Java code with indentation. The result also contains many unwanted characters.
I have used following code.
var editor = ace.edit('editor');
var code = editor.getValue();
Before my code is executed
After my code is executed
But when I run same code from developer console, it works fine.
Please suggest what is wrong or any other way to get full code with formatting using DOM element?

This happens because code in chrome extension doesn't have access to the code running in the page.
When you call ace.edit on existing editor env property of the element and creates a new editor instead.
As a workaround you can create a content script which will run in the page context, and communicate with the rest of extensions using events or postMessage. See https://stackoverflow.com/a/13292994/1743328 for more details

Related

Check where/which line or document a script gets called

I'm having a JavaScript debugging question. I would like to know, how it would be possible to find out in which file/line a new script is loaded and called. My website has several scripts which are appended via document.write(), and I would like to find a way to find the function call in all attached scripts of the website.
I would prefer either Firebug or Chrome Dev tools.
Thanks!
Neither Firebug nor the Firefox or the Chrome DevTools currently allow to debug code inserted via document.write(). I created bug 1122222 for the Firefox DevTools and issue 449269 for the Chrome DevTools requesting to be able to debug such scripts. As upcoming Firebug versions will be based on the Firefox DevTools, it will offer this feature once the Firefox bug is fixed, so there's no need to create a separate issue for it.
Until the above bugs are fixed you need to use another method to inject your script in order to be able to debug it within the browser.
Method 1: using eval()
You can use the eval() function to evaluate arbitrary code dynamically. Note that the eval() only evaluates JavaScript code, it must not be surrounded by any HTML.
Example:
eval("console.log('Hi!')");
Method 2: injecting a <script> tag
You can add a <script> tag to the page and then add contents to it.
Example:
var script = document.createElement("script");
script.textContent = "console.log('Hi!');";
document.body.appendChild(script);
Method 3: using new Function()
You can create a new function via the Function constructor.
Example:
(new Function("console.log('Hi!');"))();
Note that JavaScript won't be executed using innerHTML or insertAdjacentHTML() due to security reasons.

How to debug javascript in Visual Studio 2013

We are trying to build a Windows 8 native application using JavaScript. We are using jQuery to dynamically load the javascripts files, and all the javascript files are stored inside of the app. When I try to debug the javascript, the breakpoint can't hit, saying "The breakpoint will not currently be hit....", but in the Solution Explorer, there is a Script Documents project, there is a file called "script block", which contains all the javascripts which are loaded from jQuery. I can debug from there after I disable the "Enable Just My Code", but it's difficult to find the right place to put breakpoint, since this file is huge...
Actually all the javascript files are having sourcemap attribute, for example: //# sourceURL=ms-appx://d664ef20-6ac8-11e4-ab78-2f4dc8b50d53/www/resources/abc.js
It is working fine with all the browsers, IE, Safari, Firefox and Chrome. But Visual Studio seems not be able to recognize them.
Anyone who has the same issue?
Regards,
Xiaojun
I expect you are doing this, which evals the contents as a string, causing the string to be added to the "eval code" file under Script Documents. Note, you can still set breakpoints, you just have to do it from the "eval code" document.
// eval via AJAX -- adds to the "eval code" document
$.ajax("./js/fileToAdd.js").done(function (data) {
window.eval(data);
});
If you load the file via a script tag, the script file is loaded separately and breakpoints bind as expected because the contents are tied to the file and not a string. Here's how:
// Add <script> tag to head -- Causes script file to be loaded/displayed individually
var scriptTag = document.createElement("script");
scriptTag.src = "./js/fileToAdd.js"
document.head.appendChild(scriptTag);

Running code snippets from Google Chrome console command line, using (experimental) code snippets feature?

Reference:
Using the new code snippets feature in google chrome
I am using the code snippets in google chrome, so say I have a snippet file.
check_consistency.js
Is there an api or a global object through which we can run the snippet directly from the command line, something like:
window.runSnippet('check_consistency.js')
or maybe call methods defined in the snippet directly.
Workflow Tip 1
I also want to see this functionality added. Meanwhile, perhaps try opening the Sources where (as you know) you can select a snippet and right click it to run it. You may or may not know that you can tap Esc on this page in order to show the console at the same time as your snippets:
Workflow Tip 2
The snippets documentation also mentions
The ability to quickly locate a specific file can be essential to a developer's workflow. The DevTools allow you to search across all script, stylesheet and snippet files using the following shortcuts:
Ctrl + O (Windows, Linux)
Cmd + O (Mac OSX)
which will work regardless of the panel you are currently in.
...and...
A keyboard shortcut is also available for easily executing a snippet - just select your snippet then use Ctrl/Cmd + Enter to run it. This replicates the behavior of the Run (>) button - currently in the Sources console, but which will be moving into the debugger control in the near future.
What this means is that while in the console you can press Ctrl/Cmd+O to quickly select your snippet, and then press Cmd/Control+Enter to run it.
I have a work around for when I'm running snippets a bunch of times on a site. I wrap my snippet code in a function and assign it to a global variable.
e.g.,
window.mySnippet = function (value) {
console.log(value.toUpperCase());
};
When I run this snippet I can now run
mySnippet('hello world');
-> "HELLO WORLD"
You still have to run the snippet once to load it into memory, but it's better than nothing.

Is there a way to create and run javascript in Chrome?

Is there a way, like an extension or application, in Chrome to create and run .js files in Chrome?
if you don't want to explicitly create a js file but still want to test your javascript code, you can use snippets to run your JS code.
Follow the steps here:
Open Dev Tools
Go to Sources Tab
Under Sources tab go to snippets, + New snippet
Paste your JS code in the editor then run Command + Enter on a Mac, or Ctrl + Enter on Windows or Linux. You should see the output in console if you are using console.log or similar to test. You can edit the current web page that you have open or run scripts, load more javascript files. (Just note: this snippets are not stored on as a js file, unless you explicitly did, on your computer so if you remove chrome you will lose all your snippets);
You also have a option to save as your snippet if you right click on your snippet.
Try this:
1. Install Node.js from https://nodejs.org/
2. Place your JavaScript code into a .js file (e.g. someCode.js)
3. Open a cmd shell (or Terminal on Mac) and use Node's Read-Eval-Print-Loop (REPL) to execute someCode.js like this:
> node someCode.js
Hope this helps!
You should write in file:
<script>
//write your JavaScript code here
</script>
save it with .html extension and open with browser.
For example:
// this is test.html
<script>
alert("Hello");
var a = 5;
function incr(arg){
arg++;
return arg;
}
alert(a);
</script>
You need an HTML page to load a JS file.
You don't necessarily need to have an HTML page. Open Chrome, press Ctrl+Shift+j and it opens the JavaScript console where you can write and test your code.
- Chrome JavaScript Console
How to create a Javascript Bookmark in Chrome:
You can use a Javascript bookmark: https://helloacm.com/how-to-write-chrome-bookmark-scripts-step-by-step-tutorial-with-a-steemit-example/. Just create a bookmark to look like this:
Ex:
Name:
Test javascript bookmark in Chrome
URL:
javascript:alert('Hello world!');
Just precede the URL with javascript:, followed by your Javascript code. No space after the colon is required.
Here's how it looks as I'm typing it in:
Now save and then click on your newly-created Javascript bookmark, and you'll see this:
You can do multi-line scripts too. If you include any comments, however, be sure to use the C-style multi-line comments ONLY (/* comment */), and NOT the C++-style single-line comments (// comment), as they will interfere. Here's an example:
URL:
javascript:
/* This is my javascript demo */
function multiply(a, b)
{
return a * b;
}
var a = 1.4108;
var b = 3.7654;
var result = multiply(a, b);
alert('The result of ' + a + ' x ' + b + ' = ' + result.toFixed(4));
And here's what it looks like as you edit the bookmark, after copying and pasting the above multi-line script into the URL field for the bookmark:
.
And here's the output when you click on it:
References:
https://superuser.com/questions/192437/case-sensitive-searches-in-google-chrome/582280#582280
https://gist.github.com/borisdiakur/9f9d751b4c9cf5acafa2
Google search for "chrome javascript() in bookmark"
https://helloacm.com/how-to-write-chrome-bookmark-scripts-step-by-step-tutorial-with-a-steemit-example/
https://helloacm.com/how-to-write-chrome-bookmark-scripts-step-by-step-tutorial-with-a-steemit-example/
https://javascript.info/hello-world
JavaScript equivalent to printf/String.Format
Usually one uses text editor to create source files (like JavaScript). I use VisualStudio which have intellisence supprt for JavaScript, but any other editor will do (vim or notepad on Windows are both fine).
To run JavaScript by itself you need something that can do that. I.e. on Windows you can directly run script from console using CScript script.js command. There are other ways to run JavaScript on Windows and other OS.
Browsers (like Chrome) do not run JavaScript by itself, only as part of a page or extensions. It is unclear what one would expect of browser to do with JavaScript by itself.
You can also open your js file path in the chrome browser which will only display text.
However you can dynamically create the page by including:
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'myjs.js';
document.head.appendChild(script);
Now you can have access to the js variables and functions in the console.
Now when you explore the elements it should have included.
So i guess you dont need a html file.
The easiest way is to run js file is to install nodejs in Your system and then go to the directory like shown in the below link click to show picture
first, write node keyword and then type the name of your file
so to run your js code in node write like i.e. node index
I hope you understand this
Open a basic text editor and type out your html. Save it as .html
If you type in file:///C:/ into the address bar you can then navigate to your chosen file and run it.
If you want to open a file that is on a server type in file:/// and instead of C:/ the first letter of the server followed by :/.

How to help the debugger see my javascript, or how to best refactor my script to help make it debugger-friendly?

I have an ASP.NET MVC project that uses some simple AJAX functionality through jQuery's $.get method like so:
$.get(myUrl, null, function(result) {
$('#myselector').html(result);
});
The amount of content is relatively low here -- usually a single div with a short blurb of text. Sometimes, however, I am also injecting some javascript into the page. At some point when I dynamically include script into content that was itself dynamically added to the page, the script still runs, but it ceases to be available to the debugger. In VS2008, any breakpoints are ignored, and when I use the "debugger" statement, I get a messagebox saying that "no source code is available at this location." This fails both for the VS2008 debugger and the Firebug debugger in Firefox. I have tried both including the script inline in my dynamic content and also referencing a separate js file from this dynamic content -- both ways seemed to result in script that's unavailable to the debugger.
So, my question is twofold:
Is there any way to help the debugger recognize the existence of this script?
If not, what's the best way to include scripts that are used infrequently and in dynamically generated content in a way that is accessible to the debuggers?
I can not comment yet, but I can maybe help answer. As qwerty said, firefox console can be the way to go. I'd recommend going full bar and getting firebug. It hasn't ever missed code in my 3 years using it.
You could also change the way the injected javascript is added and see if that effects the debugger you're using. (I take it you're using Microsoft's IDE?).
In any case, I find the best way to inject javascript for IE is to put it as an appendChild in the head. In the case that isn't viable, the eval function (I hate using it as much as you do) can be used. Here is my AJAX IE fixer code I use. I use it for safari too since it has similar behavior. If you need that too just change the browser condition check (document.all for IE, Safari is navigator.userAgent.toLowerCase() == 'safari';).
function execajaxscripts(obj){
if(document.all){
var scripts = obj.getElementsByTagName('script');
for(var i=0; i<scripts.length; i++){
eval(scripts[i].innerHTML);
}
}
}
I've never used jquery, I preferred prototype then dojo but... I take it that it would look something like this:
$.get(myUrl, null, function(result) {
$('#myselector').html(result);
execajaxscripts(result);
});
The one problem is, eval debug errors may not be caught since it creates another instance of the interpreter. But it is worth trying.. and otherwise. Use a different debugger :D
This might be a long shot, but I don't have access to IE right now to test.
Try naming the anonymous function, e.g.:
$.get(myUrl, null, function anon_temp1(result) {
$('#myselector').html(result);
});
I'm surprised firebug is not catching the 'debugger' statement. I've never had any problems no matter how complicated the JS including method was
If this is javascript embedded within dynmically generated HTML, I can see where that might be a problem since the debugger would not see it in the initial load. I am surprised that you could put it into a seperate .js file and the debugger still failed to see the function.
It seems you could define a function in a seperate static file, nominally "get_and_show" (or whatever, possibly nested in a namespace of sorts) with a parameter of myUrl, and then call the function from the HTML. Why won't that trip the breakpoint (did you try something like this -- the question is unclear as to whether the reference to the .js in the dynamic HTML was just a func call, or the actual script/load reference as well)? Be sure to first load the external script file from a "hard coded" reference in the HTML file? (view source on roboprogs.com/index.html -- loads .js files, then runs a text insertion func)
We use firebug for debug javascript, profile requests, throw logs, etc.
You can download from http://getfirebug.com/
If firebug don't show your javascript source, post some url to test your example case.
I hope I've been of any help!
If you add // # sourceURL=foo.js to the end of the script that you're injecting then it should show up in the list of scripts in firebug and webkit inspector.
jQuery could be patched to do this automatically, but the ticket was rejected.
Here's a related question: Is possible to debug dynamic loading JavaScript by some debugger like WebKit, FireBug or IE8 Developer Tool?

Categories