How to embed Firebug Lite in my QWebView widget? - debugging

I've started to embed some QWebView widgets to my desktop application (PyQt).
I use JQuery and CSS to enhance appearance and usability.
It would be comfortable to debug my html code with a web inspector.
How can I embed Firebug Lite in my QWebView widgets?
E.g. I tried the following code and it doesn't work:
html1 = """
<html debug="true">
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.6.1.js"></script>
<script type="text/javascript" src="https://getfirebug.com/firebug-lite.js#startOpened=true"></script>
<script type="text/javascript">
$(document).ready(function() {
$("body").css("background", "#f00");
console.log("in here");
});
</script>
</head>
<body><h1>Hello!</h1></body>
</html>
"""
html2 = """
<html debug="true">
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.6.1.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("body").css("background", "#f00");
var firebugLite = document.createElement("script");
firebugLite.src = "https://getfirebug.com/firebug-lite.js";
firebugLite.id = "firebug_lite";
firebugLite.textContent = "{ startOpened: true }";
document.getElementsByTagName("head")[0].appendChild(firebugLite);
console.log("in here");
});
</script>
</head>
<body><h1>Hello!</h1></body>
</html>
"""
if __name__ == '__main__':
app = QApplication(sys.argv)
view = QWebView()
frame = view.page().mainFrame()
frame.setHtml(html2)
view.show()
app.exec_()
html1 and html2 have the same effect: body turns into red but Firebug doesn't show up.
P.S. my actual html code can't be debug with an external client browser,
because it uses QT resources and application window objects.

I've added this JavaScript to my WebKit-based projects, maybe this helps for QWebView as well?
var firebugLite = document.createElement("script");
firebugLite.src = "https://getfirebug.com/firebug-lite.js";
firebugLite.id = "firebug_lite";
firebugLite.textContent = "{ startOpened: true }";
document.getElementsByTagName("head")[0].appendChild(firebugLite);

Related

Rx.js observable subscribe - button click not caught

I'm trying a very basic example with Rx.js observable-subscribe. Here is my code:
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"></meter>
<title></title>
</head>
<body>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/5.4.0/Rx.js"></script>
<script src="https://code.jquery.com/jquery-3.4.0.min.js" integrity="sha256-BJeo0qm959uMBGb65z40ejJYGSgR7REI4+CW1fNKwOg=" crossorigin="anonymous"></script>
<script src="index.js"></script>
<button id='testButton'>Click</button>
</body>
</html>
JS
var button = $('#testButton');
var btn$ = Rx.Observable.fromEvent(button, 'click');
btn$.subscribe(function(e){
console.log(e);
});
But there is nothing in the console when I click the button. Did I miss something?
fromEvent requires the first argument to be DOM element. $ probably refers to jQuery which returns a jQuery object.
So you should pull the native element from button before passing it to fromEvent:
var button = $('#testButton');
var btn$ = Rx.Observable.fromEvent(button[0], 'click'); // or .get(0) instead of [0]
Live demo: https://stackblitz.com/edit/rxjs-lpvsng?file=index.ts
I wrapped my JS code to jquery '$( document ).ready()' handler and it started working:
$( document ).ready(function() {
var button = $('#testButton');
var btn$ = Rx.Observable.fromEvent(button, 'click');
btn$.subscribe(function(e){
console.log(e);
});
});

Thymeleaf th:inline="javascript" issue

I don't know how to solve the following: I'd like to let my Model generate real javascript dynamically based on some model logic.
This final piece of javascript code then should be added inside the $(document).ready { } part of my html page.
The thing is: If I use inline="javascript", the code gets quoted as my getter is a String (that is how it is mentioned in the Thymeleaf doc but it's not what I need ;-)
If I use inline="text" in is not quoted but all quotes are escaped instead ;-) - also nice but unusable 8)
If I try inline="none" nothing happens.
Here are the examples
My model getter created the following Javascript code.
PageHelper class
public String documentReady() {
// do some database operations to get the numbers 8,5,3,2
return "PhotoGallery.load(8,5,3,2).loadTheme(name='basic')";
}
So if I now try inline="javascript"
<script th:inline="javascript">
/*<![CDATA[*/
jQuery().ready(function(){
/*[[${pageHelper.documentReady}]]*/
});
/*]]>*/
</script>
it will be rendered to
<script>
/*<![CDATA[*/
jQuery().ready(function(){
'PhotoGallery.load(8,5,3,2).loadTheme(name=\'basic\')'
});
/*]]>*/
</script>
Which doesn't help as it is a String literal, nothing more (this is how Thymeleaf deals with it).
So if I try inline="text" instead
<script>
/*<![CDATA[*/
jQuery().ready(function(){
PhotoGallery.load(8,5,3,2).loadTheme(name='basic')
});
/*]]>*/
</script>
Which escapes the quotes.
inline="none" I do not really understand, as it does nothing
<script>
/*<![CDATA[*/
jQuery().ready(function(){
[[${pageHelper.documentReady}]]
});
/*]]>*/
</script>
To be honest I have no idea how to solve this issue and hopefully anybody out there knows how to deal with this.
Many thanks in advance
Cheers
John
I would change the approach.
Thymeleaf easily allows you to add model variables in your templates to be used in Javascript. In my implementations, I usually put those variables somewhere before the closing header tag; to ensure they're on the page once the JS loads.
I let the template decide what exactly to load, of course. If you're displaying a gallery, then render it as you would and use data attributes to define the gallery that relates to some JS code. Then write yourself a nice jQuery plugin to handle your gallery.
A relatively basic example:
Default Layout Decorator: layout/default.html
<!doctype html>
<html xmlns:layout="http://www.thymeleaf.org" xmlns:th="http://www.thymeleaf.org">
<head>
<title>My Example App</title>
<object th:remove="tag" th:include="fragments/scripts :: header" />
</head>
<body>
<div layout:fragment="content"></div>
<div th:remove="tag" th:replace="fragments/scripts :: footer"></div>
<div th:remove="tag" layout:fragment="footer-scripts"></div>
</body>
</html>
The thing to notice here is the inclusion of the generic footer scripts and then a layout:fragment div defined. This layout div is what we're going to use to include our jQuery plugin needed for the gallery.
File with general scripts: fragments/scripts.html
<div th:fragment="header" xmlns:th="http://www.thymeleaf.org">
<script type="text/javascript" th:inline="javascript">
/*<![CDATA[*/
var MY_APP = {
contextPath: /*[[#{/}]]*/,
defaultTheme: /*[[${theme == null} ? null : ${theme}]]*/,
gallery: {
theme: /*[[${gallery == null} ? null : ${gallery.theme}]]*/,
images: /*[[${gallery == null} ? null : ${gallery.images}]]*/,
names: /*[[${gallery == null} ? null : ${gallery.names}]]*/
}
};
/*]]>*/
</script>
</div>
<div th:fragment="footer" xmlns:th="http://www.thymeleaf.org">
<script type="text/javascript" src="/js/jquery.js"></script>
<script type="text/javascript" src="/js/my_app.js"></script>
</div>
In the scripts file, there are 2 fragments, which are included from the decorator. In the header fragment, a helpful context path is included for the JS layer, as well as a defaultTheme just for the hell of it. A gallery object is then defined and assigned from our model. The footer fragment loads the jQuery library and a main site JS file, again for purposes of this example.
A page with a lazy-loaded gallery: products.html
<html layout:decorator="layout/default" xmlns:layout="http://www.thymeleaf.org/" xmlns:th="http://www.thymeleaf.org">
<head>
<title>Products Landing Page</title>
</head>
<body>
<div layout:fragment="content">
<h1>Products</h1>
<div data-gallery="lazyload"></div>
</div>
<div th:remove="tag" layout:fragment="footer-scripts">
<script type="text/javascript" src="/js/my_gallery.js"></script>
</div>
</body>
</html>
Our products page doesn't have much on it. Using the default decorator, this page overrides the page title in the head. Our content fragment includes a title in an h1 tag and an empty div with a data-gallery attribute. This attribute is what we'll use in our jQuery plugin to initialize the gallery.
The value is set to lazyload, so our plugin knows that we need to find the image IDs in some variable set somewhere. This could have easily been empty if the only thing our plugin supports is a lazyloaded gallery.
So the layout loads some default scripts and with cleverly placed layout:fragments, you allow certain sections of the site to load libraries independent of the rest.
Here's a basic Spring controller example, to work with our app: MyController.java
#Controller
public class MyController {
#RequestMapping("/products")
public String products(Model model) {
class Gallery {
public String theme;
public int[] images;
public String[] names;
public Gallery() {
this.theme = "basic";
this.images = new int[] {8,5,3,2};
this.names = new String[] {"Hey", "\"there's\"", "foo", "bar"};
}
}
model.addAttribute("gallery", new Gallery());
return "products";
}
}
The Gallery class was tossed inline in the products method, to simplify our example here. This could easily be a service or repository of some type that returns an array of identifiers, or whatever you need.
The jQuery plugin that we created, could look something like so: my_gallery.js
(function($) {
var MyGallery = function(element) {
this.$el = $(element);
this.type = this.$el.data('gallery');
if (this.type == 'lazyload') {
this.initLazyLoadedGallery();
}
};
MyGallery.prototype.initLazyLoadedGallery = function() {
// do some gallery loading magic here
// check the variables we loaded in our header
if (MY_APP.gallery.images.length) {
// we have images... sweet! let's fetch them and then do something cool.
PhotoGallery.load(MY_APP.gallery.images).loadTheme({
name: MY_APP.gallery.theme
});
// or if load() requires separate params
var imgs = MY_APP.gallery.images;
PhotoGallery.load(imgs[0],imgs[1],imgs[2],imgs[3]).loadTheme({
name: MY_APP.gallery.theme
});
}
};
// the plugin definition
$.fn.myGallery = function() {
return this.each(function() {
if (!$.data(this, 'myGallery')) {
$.data(this, 'myGallery', new MyGallery(this));
}
});
};
// initialize our gallery on all elements that have that data-gallery attribute
$('[data-gallery]').myGallery();
}(jQuery));
The final rendering of the products page would look like so:
<!doctype html>
<html>
<head>
<title>Products Landing Page</title>
<script type="text/javascript">
/*<![CDATA[*/
var MY_APP = {
contextPath: '/',
defaultTheme: null,
gallery: {
theme: 'basic',
images: [8,5,3,2],
names: ['Hey','\"there\'s\"','foo','bar']
}
};
/*]]>*/
</script>
</head>
<body>
<div>
<h1>Products</h1>
<div data-gallery="lazyload"></div>
</div>
<script type="text/javascript" src="/js/jquery.js"></script>
<script type="text/javascript" src="/js/my_app.js"></script>
<script type="text/javascript" src="/js/my_gallery.js"></script>
</body>
</html>
As you can see, Thymeleaf does a pretty good job of translating your model to valid JS and actually adds the quotes where needed and escapes them as well. Once the page finishes rendering, with the jQuery plugin at the end of the file, everything needed to initialize the gallery should be loaded and ready to go.
This is not a perfect example, but I think it's a pretty straight-forward design pattern for a web app.
instead of ${pageHelper.documentReady} use ${pageHelper.documentReady}

Responsive Picture Element still working even after being removed from DOM in Chrome Browser

Can anyone explain why the responsive picture image is still firing using Chrome Canary 42.0.2302.2 after it has been removed (works as expected in IE11 and FF 35.0.1 - in Chrome 40.0.2214.111 m it is broken, but interestingly, it also downloaded both images straight away!).
To test, open the test page with Chrome Dev Tools open on the Network tab. Take note of the image that has been displayed. Tap anywhere on the page to empty the content. Now resize the page and note that the other images are downloaded despite the picture element being removed from the page.
<!DOCTYPE html>
<html>
<head>
<title>Test Picture Element</title>
<meta charset="utf-8">
</head>
<body>
<picture>
<source srcset="http://placehold.it/768/f00/fff" media="(max-width: 768px)">
<source srcset="http://placehold.it/992/0f0/fff" media="(max-width: 992px)">
<img srcset="http://placehold.it/1200/00f/fff">
</picture>
</body>
<script src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
<script type="text/javascript">
$(function(){
$('body').on('click', function() {
$('body').empty();
});
});
</script>
</html>
JSFiddle for your convenience: http://jsfiddle.net/5qwLus59/4/
Because Mutations aren't set up correctly in Chrome. It's similar to how people sometimes write their JS code.
For example:
$('.nav').each(function(){
var $nav = $(this);
var sizeNav = function(){
//some code
};
$(window).on('resize', sizeNav);
});
In fact they should do something like this:
$('.nav').each(function(){
var $nav = $(this);
var sizeNav = function(){
//some code
};
$(window).on('resize', sizeNav);
$nav.on('remove', function(){
//destroy code
$(window).off('resize', sizeNav);
});
});
This is a serious issue, please report this!:
https://code.google.com/p/chromium/issues

How to make a ajax loading component by using angularjs service?

I want to make a specific component for showing loading icon when the browser waits to load data from json. Is there any possible way to do it by using a service ??
html :
<html ng-app="app">
<head>
<title> ERP </title>
</head>
<body >
<div ng-controller="data"><span class="loading" ng-show="loader"><img src="ajax-loader.gif"></span>
<table>
<tr><td>{{data1}}</td><td>{{data1}}</td><td>{{data1}}</td></tr>
</table>
</div>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script>
<script type="text/javascript" src="ctrl.js"></script>
</body>
</html>
js :
var app = angular.module('app',[]);
app.controller('data', ['$scope','$http',function($scope,$http){
$scope.loader = null ;
if($scope.loader == null )
{
$scope.loader = true ;
}
$http.get('events.json').
success(function(data) {
$scope.loader = false ;
console.log(data);
$scope.data1 = data ;
console.log($scope.data1);
}).
error(function(data, status, headers, config) {
});
}]);
You can wrap the original $http to provide a customizedHttp service. in this service, provide the same interface with $http. when sending GET request to the server, the customizedHttp broadcast an event to show the loading flag. and after receiving response, broadcast another event to hide the loading flag.
to control the flag, you'd better to write a directive.

How to inject dependencies in jasmine test for an angular item

Here is the test spec file:
describe('Test main controller', function(){
it('Should initialize value to Loading', function(){
$scope = {}
ctrl = new mainNavController($scope)
expect($scope.wksp_name).toBe('Loading')
})
})
Here is the controller file
function mainNavController($scope) {
$scope.wksp_name = 'Loading...'
$scope.$on('broadCastWkspNameEvent', function (e, args) {
$scope.wksp_name = args
})
}
mainNavController.$inject=['$scope']
But my test fails saying Object #<Object> has no method '$on'
I am using the basic setup of jasmine.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Jasmine Spec Runner</title>
<link rel="shortcut icon" type="image/png" href="testlib/jasmine-1.2.0/jasmine_favicon.png">
<link rel="stylesheet" type="text/css" href="testlib/jasmine-1.2.0/jasmine.css">
<script type="text/javascript" src="testlib/jasmine-1.2.0/jasmine.js"></script>
<script type="text/javascript" src="testlib/jasmine-1.2.0/jasmine-html.js"></script>
<!-- include source files here... -->
<script type="text/javascript" src="/static_files/js/test-specs/main-nav-spec.js"></script>
<!-- include spec files here... -->
<script type="text/javascript" src="/static_files/js/common/jquery/latest.js"></script>
<script type="text/javascript" src="/static_files/js/common/angular/angular-1.0.1.min.js"></script>
<script type="text/javascript" src="/static_files/js/common/angular/angular-resource-1.0.1.min.js"></script>
<script type="text/javascript" src="/static_files/js/section/main-nav-controller.js"></script>
<script type="text/javascript">
(function() {
var jasmineEnv = jasmine.getEnv();
jasmineEnv.updateInterval = 1000;
var htmlReporter = new jasmine.HtmlReporter();
jasmineEnv.addReporter(htmlReporter);
jasmineEnv.specFilter = function(spec) {
return htmlReporter.specFilter(spec);
};
var currentWindowOnload = window.onload;
window.onload = function() {
if (currentWindowOnload) {
currentWindowOnload();
}
execJasmine();
};
function execJasmine() {
jasmineEnv.execute();
}
})();
</script>
</head>
<body>
</body>
</html>
What is it that I am doing wrong? I am not able to understand how this thing is supposed to work :)
The main problem with your test code is that it tries to create a controller's instance "by hand" using the new operator. When doing so AngularJS has no chance to inject dependencies. What you should be doing is to allow AngularJS inject dependencies:
var $scope, ctrl;
//you need to inject dependencies first
beforeEach(inject(function($rootScope) {
$scope = $rootScope.$new();
}));
it('Should initialize value to Loading', inject(function($controller) {
ctrl = $controller('MainNavController', {
$scope: $scope
});
expect($scope.wksp_name).toBe('Loading...');
}));
Here is the link to a complete jsFiddle: http://jsfiddle.net/pkozlowski_opensource/7a7KR/3/
There are 2 things worth noting in the above example:
You can use the inject() method from the ngMock module to inject dependencies: https://docs.angularjs.org/api/ngMock/function/angular.mock.inject
To create a controller instance (that supports dependency injection) you would use the $controller service: http://docs.angularjs.org/api/ng.$controller
As the last remark: I would advise naming controllers starting with an uppercase letter - this way we won't confuse them with variable names.
Great answer by #pkozlowski.opensource. To elaborate a bit more... Sometimes it could be also handy to assert that $scope.$on was really called by your controller. In this case you can spy on $scope.$on as pointed out below:
beforeEach(inject(function($rootScope) {
$scope = $rootScope.$new();
spyOn($scope, '$on').andCallThrough();
}));
And then you can assert that $on was called with your event name and some function as arguments:
it('Should bind to "broadCastWkspNameEvent"', inject(function($controller) {
ctrl = $controller('MainNavController', {
$scope: $scope
});
expect($scope.$on).toHaveBeenCalledWith('broadCastWkspNameEvent', jasmine.any(Function));
}));
I agree with pkozowski's response, but to answer your question more directly, you need to stub out '$on'
Your example would pass if your $scope looked like:
$scope = {
$on: function() {}
}

Resources