how to debug the js in jsfiddle - debugging

I am looking at this jsfiddle: http://jsfiddle.net/carpasse/mcVfK/
It works fine that is not the problem , I just want to know how to debug through the javascript. I tried to use the debugger command and I cant find it in the sources tab?
any idea how I can debug this?
some code from the fiddle:
angular.module('app', ['appServices'])
.config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/home', {templateUrl: 'home.html', controller: HomeCtrl}).
when('/list', {templateUrl: 'list.html', controller: ListCtrl}).
when('/detail/:itemId', {templateUrl: 'detail.html', controller: DetailCtrl}).
when('/settings', {templateUrl: 'settings.html', controller: SettingsCtrl}).
otherwise({redirectTo: '/home'});
}]);

The JavaScript is executed from the fiddle.jshell.net folder of the Sources tab of Chrome. You can add breakpoints to the index file shown in the Chrome screenshot below.

Use the debugger; statement in the code. The browser inserts a breakpoint at this statement, and you can continue in browser's debugger.
This should work atleast in chrome and firefox.
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Statements/debugger
angular.module('app', ['appServices'])
.config(['$routeProvider', function($routeProvider) {
// *** Debugger invoked here
debugger;
$routeProvider.
when('/home', {templateUrl: 'home.html', controller: HomeCtrl}).
when('/list', {templateUrl: 'list.html', controller: ListCtrl}).
when('/detail/:itemId', {templateUrl: 'detail.html', controller: DetailCtrl}).
when('/settings', {templateUrl: 'settings.html', controller: SettingsCtrl}).
otherwise({redirectTo: '/home'});
}]);

Something worth mentioning. If you are ever using chrome dev tools. Press ctrl+shift+F and you can search through all the files in the source.

In addition to the other answers.
Very often it is useful just write debug information into the console:
console.log("debug information here");
The output is available in browsers dev tools console. Like it was logged from the usual javascript code.
This is quite simple and effective.

Adding a debugger statement in the code and enable the "Developer Tools" in the bowser.
Then when you are running the code in JSFiddle, the debugger will be hit!.

One of the answers above works but just that you need to add the keyword debugger at the line you want the break points and run the code which will then fire them on the dev tool. The code then gets visible at the source tab under editor_console=true.

Here is another place :)
Under the Jsfiddle.net node.

The JavaScript is executed from the file ?editor_console=true in the folder result (fiddle.jshell.net)/fiddle.jshell.net/_display folder of the Sources tab of Chrome when using the developper tool. You can add breakpoints to your code then and refresh the page.
More information on using chrome debugger can be found at Trying to debug Javascript in Chrome

Related

How can I disable the Preview button while in Source Mode with CKEditor 4?

We are using the latest version 4.7.3 of CKEditor (Full) available from nuget. We've tried a number of suggested solutions to disable the Preview toolbar button while in Source Mode, but could not get it to work. There are cases when there are more than one editor on a page, and they are added as user controls (.ascx) due to some unrelated logic. For example we've tried the below:
CKEDITOR.on('instanceReady', function (instance) {
instance.editor.addCommand('preview', {
modes: { wysiwyg: 1, source: 0 }
});
});
We configure the toolbar buttons via config.js.
CKEDITOR.editorConfig = function (config) {
config.toolbar_CMToolbar =
[
{ name: 'sourcedialog', items: ['Source', '-', 'Preview'] }
];
};
The reason we need this is to avoid a security issue when malicious script has been added while in Source Mode and the Preview was immediately requested, causing javascript to execute. Ordinarily the wysiwyg mode would clean this up and the malicious scripts would have been validated.
Below is the sample script that triggers the issue, for reference. (include everything from double-quote to tag close)
"><img src=x onerror=alert(7)>
Granted this is just evading the main issue rather than fixing it, but this workaround would be handled quicker.
Hoping to hear suggestions on how to correct this. Thanks!
You can change properties of commands like this:
CKEDITOR.on('instanceReady', function(evt) {
evt.editor.commands.preview.modes.source = 0;
});

how to access Angular2 component specific data in console?

Is there any way to access Angular2 specific component specific data in console, for debugging purpose?
Like Angular1 has capability to access its components value in console.
update 4.0.0
StackBlitz example
update RC.1
Plunker example In the browser console on the top-left (filter symbol) select plunkerPreviewTarget (or launch the demo app in its own window) then enter for example
Select a component in the DOM node and execute in the console
ng.probe($0);
or for IE - thanks to Kris Hollenbeck (see comments)
ng.probe(document.getElementById('myComponentId')).componentInstance
Alternative
Hint: enabling debug tools overrides ng.probe()
Enable debug tools like:
import {enableDebugTools} from '#angular/platform-browser';
bootstrap(App, []).then(appRef => enableDebugTools(appRef))
Use above Plunker example and in the console execute for example:
ng.profiler.appRef
ng.profiler.appRef._rootComponents[0].instance
ng.profiler.appRef._rootComponents[0].hostView.internalView
ng.profiler.appRef._rootComponents[0].hostView.internalView.viewChildren[0].viewChildren
I haven't found a way yet to investigate the Bar directive.
A better debug experience is provided by Augury which builds on this API
https://augury.angular.io/
https://www.youtube.com/watch?v=b1YV9vJKXEA
original (beta)
Here is a summary how to do that https://github.com/angular/angular/blob/master/TOOLS_JS.md (dead link and I haven't found a replacement).
Enabling debug tools
By default the debug tools are disabled. You can enable debug tools as follows:
import {enableDebugTools} from 'angular2/platform/browser';
bootstrap(Application).then((appRef) => {
enableDebugTools(appRef);
});
Using debug tools
In the browser open the developer console (Ctrl + Shift + j in Chrome). The top level object is called ng and contains more specific tools inside it.
Example:
ng.profiler.timeChangeDetection();
See also
Angular 2: How enable debugging in angular2 from browser console
First select the element using chrome 'inspect element' and run below method in chrome 'developer console'.
ng.probe($0).componentInstance
You could also use a css selector as shown below.
ng.probe($$('.image-picker')[0]).componentInstance
If you do it often, to make it little easier, have a global shortcut created as below. Now select any DOM element inside the component using 'inspect element' and invoke 'e()' from console
window['e'] = () => eval('ng.probe($0).componentInstance');
Using global scope variable.(any browser)
In ngOnInit() of component file
ngOnInit() {
window['test'] = this;
}
Now we can access instance of that component including services(imported on that component).
If you want to prevent accessing test for let's say production, you can conditionally give access to test like:
constructor(private _configService: ConfigService) {
}
ngOnInit() {
if(_configService.prod) {
window['test'] = this;
}
}
Here _configService means the instance of service used by all components and services.
So variable would be set like:
export class ConfigService {
prod = false;
}
I'm surprised that no one has mentioned Augury here, it's a Chrome plugin that gives you convenient access to all the information in your components, and also makes it easier to see that information in the console directly:
https://augury.rangle.io/
Angular 9+:
Select component root element in developer tools (Inspector), then type in console:
ng.getComponent($0);

Modernizr.videoautoplay object shows true, Modernizr.videoautoplay returning undefined

I'm using a custom Modernizr build, v3.3.0. I've created a simple JSFiddle example to illustrate: https://jsfiddle.net/cqkg7x45/6/.
console.log(Modernizr);
will show the Modernizr object, and when I inspect it in the JS console I can see "videoautoplay" is a property with a value of "true".
But, when I do
console.log(Modernizr.videoautoplay)
it returns "undefined".
I was originally seeing this issue in a WordPress theme I'm developing, but was also able to recreate in JSFiddle and a separate stand-alone HTML page. Also, Modernizr is putting the "videoautoplay" class on my HTML tag, even when I know the device does not support that feature (iPhone 5).
Update: This issue appears to be happening in Chrome (v47.0.2526.106), but not Firefox (v43.0.2).
I'm going to answer my own question in case anyone else runs into this problem. I found the solution on this SO post: How do I detect if the HTML5 autoplay attribute is supported?.
Since this is an "async" test you can't access the property using the syntax
Modernizr.videoautoplay
You have to use the .on() function, as shown in the above SO post:
Modernizr.on('videoautoplay', function(result){
if(result) {
alert('video autoplay is supported');
} else {
alert('video autplay is NOT supported');
}
});

js in html is not executing in Phoenix framework sample app

I'm playing around with the phoenix framework. I copied the chat example entirely but I'm not getting any results.
In fact when I write console.log("testing") in my app.js I notice that my console does not log anything...
I am getting the error referenced in this link:
phoenix framework - invalid argument at new Socket - windows
However that error seems to be related to Brunch not working in windows. When I brunch build, I can confirm that app.js has the console.log("testing") that I included.
Nevertheless, I don't see that console log when I visit my localhost:4000.
Why is JS not executing?
Turns out the guide is missing a key line that made it not work.
The guide has the following:
<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
<script src="<%= static_path(#conn, "/js/app.js") %>"></script>
</body>
But that is missing the below line which you can put above the body tag.
<script>require("web/static/js/app")</script>
Even as Chowza already solved this question I would like to propose another, possible cleaner solution, using the autoRequire feature of Brunch.io.
The problem occurs because Brunch.io does not autoRequire the app.js under Windows correctly. Chowza worked around this issue by requiring the file manually in the html. You can omit the manual require if you alter the /brunch-config.js as follows: Change from
modules: {
autoRequire: {
"js/app.js": ["web/static/js/app"]
}
}
To
modules: {
autoRequire: {
"js/app.js": ["web/static/js/app"],
"js\\app.js": ["web/static/js/app"]
}
}
This way the app.js is autoRequired, even if you work on a Windows based system.
I would like to mention, that this solution is based on the link Chowza himself posted, so all credit goes to him for pointing to the link.

Debugging Content Scripts for Chrome Extension

General Questions
Hello! I'm delving into the world of Chrome Extensions and am having some problems getting the overall workflow down. It seems that Google has recently switched to heavily advocating Event Pages instead of keeping everything in background.js and background.html. I take part of this to mean that we should pass off most of your extension logic to a content script.
In Google's Event Page primer, they have the content script listed in the manifest.json file. But in their event page example extension, it is brought in via this code block in background.js: chrome.tabs.executeScript(tab.id, {file: "content.js"}, function() { });
What are the advantages of doing it one way over the other?
My Code
I'm going forward with the programatic way of injecting the content script, like Google's example.
manifest.json
{
"manifest_version": 2,
"name": "Test",
"description": "Let's get this sucker working",
"version": "0.0.0.1",
"permissions": [
"tabs",
"*://*/*"
],
"background": {
"scripts": ["background.js"],
"persistent": false
},
"browser_action": {
"default_icon": "icon.png"
}
}
background.js
chrome.browserAction.onClicked.addListener(function() {
console.log("alert from background.js");
chrome.tabs.executeScript({file: "jquery-2.0.2.min.js"}, function() {
console.log("jquery Loaded");
});
chrome.tabs.executeScript({file: "content.js"}, function() {
console.log("content loaded");
});
});
content.js
console.log('you\'r in the world of content.js');
var ans = {};
ans.createSidebar = function() {
return {
init: function(){
alert("why hello there");
}
}
}();
ans.createSidebar.init();
I am able to get the first 3 console.log statements to show up in the background page's debugger. I'm also able to get the alert from content.js to show up in any website. But I'm not able to see the console.log from content.js, nor am I able to view any of the JS from content.js. I've tried looking in the "content scripts" section of the background page debugger's Sources tab. A few other posts on SO have suggested adding debugger; statements to get it to show, but I'm not having any luck with anything. The closest solution I've seen is this post, but is done by listing the content script in the manifest.
Any help would be appreciated. Thanks!
Content scripts' console.log messages are shown in the web page's console instead of the background page's inspector.
Adding debugger; works if the Developer Tool (for the web page where your content script is injected) is opened.
Therefore, in this case, you should first activate the Developer Tool (of the web page) before clicking the browser action icon and everything should work just fine.
I tried to use the debuggermethod, but it doesn't not work well because the project is using require.js to bundle javascript files.
If you are also using require.js for chrome extension development, you can try adding something like this to the code base, AND change eval(xhr.responseText) to eval(xhr.responseText + "\n//# sourceURL=" + url);. (like this question)
Then you can see the source file in your dev tool (but not the background html window)
manifest v3
You can add console.log statements to your content scripts.
This is one of the best ways to debug an application.
Let's say you want to access a DOM node from the content script.
const node = document.querySelector("selector")
node will be Element instance if it exists else it will be null
If you can see the node in the Elements tab but not able to access it via content script then the node might have not been loaded at the time you accessed it.
Follow this answer to fix this issue.

Resources