Chrome Dev Tools export Elements HTML - html

To debug my chromium-embedded application I am looking for a function to get the source code of the web page from withing the chrome developer tools. I basically want the HTML tree shown in the 'Elements' tab, the actual HTML DOM, as HTML text. Does this functionality exist? How can I use it?
As I use CEF I do only have the chrome dev tools available and not the full browser. I cannot use the right-click context menu because I want to see the current manipulated DOM and not the original source.
I want to use this functionality for debugging purpose so that I can diff two different HTML trees.

Select the top node and choose "Copy". You'll have to re-add the Doctype, though.
Alternatively, you could click on "edit as HTML" and copy it from there.

update: extension has been released! Named Dump Dom
chrome store
github source
I found a better way to dump the current dom tree to a html file ( to persist your changes to the dom tree in the element tab ),just paste the code below to the console, and a dom.html file would be downloaded.
filename = "dom";
var html = '',
node = document.firstChild
while (node) {
switch (node.nodeType) {
case Node.ELEMENT_NODE:
html += node.outerHTML
break
case Node.TEXT_NODE:
html += node.nodeValue
break
case Node.CDATA_SECTION_NODE:
html += '<![CDATA[' + node.nodeValue + ']]>'
break
case Node.COMMENT_NODE:
html += '<!--' + node.nodeValue + '-->'
break
case Node.DOCUMENT_TYPE_NODE:
// (X)HTML documents are identified by public identifiers
html +=
'<!DOCTYPE ' +
node.name +
(node.publicId ? ' PUBLIC "' + node.publicId + '"' : '') +
(!node.publicId && node.systemId ? ' SYSTEM' : '') +
(node.systemId ? ' "' + node.systemId + '"' : '') +
'>\n'
break
}
node = node.nextSibling
}
var file = new Blob([html], {
type: 'text/html'
});
if (window.navigator.msSaveOrOpenBlob) // IE10+
window.navigator.msSaveOrOpenBlob(file, filename);
else { // Others
var a = document.createElement("a"),
url = URL.createObjectURL(file);
a.href = url;
a.download = filename;
document.body.appendChild(a);
a.click();
setTimeout(function () {
document.body.removeChild(a);
window.URL.revokeObjectURL(url);
}, 0);
}
Inspired from this project: https://github.com/wingleung/save-page-state.
And I would develop an extention to make on-click-dump functional later.

You can try the following:
All you have to do is right click the element and copy the outerHTML.

Related

switchTab() cannot make the tab as currentTab in WebdriverIO standalone mode

webdriverio with selenium-standalone server, without wdio.
Clicking a link to open a new tab.
I can see the new tab opened, but no elements on the new tab can be located, as if the new tab never existed.
The titles of the first tab and the new tab:
C:\Users\...\test>node switchtab.js
main window: CDwindow-(D77C1A0428E3E5717A1DF2473274B905)
Title is: WebdriverIO - WebDriver bindings for Node.js
new window: CDwindow-(D77C1A0428E3E5717A1DF2473274B905)
Title is: WebdriverIO - WebDriver bindings for Node.js
switchTab: CDwindow-(BE8C6F13723E588E3E39C7C21C02C290)
current window: CDwindow-(D77C1A0428E3E5717A1DF2473274B905)
Title is: WebdriverIO - WebDriver bindings for Node.js
It always gets the first tab id as you can see. Therefore no elements on new tab can be located.
What did I do wrong? How can I make the new tab as current tab? Even though I see the new tab becomes the active tab, but apprently the code doesn't think so.
Here is the sample code snippet:
var webdriverio = require('webdriverio');
var options = { desiredCapabilities: { browserName: 'chrome' } };
var client = webdriverio.remote(options);
var mainW, newW, newW1;
client
.init()
.url('http://webdriver.io/')
.getCurrentTabId().then(function (handle) {
mainW = handle;
console.log('main window: ' + mainW);
})
.getTitle().then(function(title) {
console.log('Title is: ' + title);
})
.waitForExist('a[href="http://try.learnwebdriverio.com"]')
.click('a[href="http://try.learnwebdriverio.com"]')
.pause(5000)
.getCurrentTabId().then(function (handle) {
newW = handle;
console.log('new window: ' + newW);
})
.getTitle().then(function(title) {
console.log('Title is: ' + title);
})
.getTabIds().then(function (handle) {
console.log('switchTab: ' + handle[1]);
newW1 = handle[1];
})
.switchTab(newW1)
.pause(5000)
.getCurrentTabId().then(function (handle) {
console.log('current window: ' + handle);
})
.getTitle().then(function(title) {
console.log('Title is: ' + title);
.end();
switchTab() won't help. After .switchTab(newW1), it still gets the first tab. And even worse, I see it physically switches to the first tab.
It works by using Testrunner (with mocha, and I think other frameworks would be just the same). The only difference between standalone mode and Testrunner mode I see is that:
Different than using the standalone mode all commands that get executed by the wdio test runner are synchronous.
Therefore, It should have something to do with synchronization, which the standalone mode doesn't handle correctly.
Please note that in Testrunner mode, the new tab is also not current after clicking the link. You have to manually switchTab() to set the new tab as current.

Flying Saucer - Open an attachment from pdf link

I would like to know if there is a way to create a link (Using HTML) to open an attachment embedded in the pdf document.
Something like this...
Open the attachment file or Open the attachment file
Any suggestion or recommendation?
Thanks
I have been able to implement this scenario after reading the next useful post
https://groups.google.com/forum/#!topic/flying-saucer-users/KuwPoTjaQYU
Steps:
Check out the next repository https://github.com/osnard/flyingsaucer
Analyse the file ITextOutputDevice.java, method processLink(RenderingContext c, Box box)
Make changes based on your needs
Build the project and use the jar file generated
Here the code to create an embedded file based on base64 content.
Java
...String doEmbedFile = handler.getAttributeValue( elem, "data-fs-embed-file" );
if ("true".equals(doEmbedFile.toLowerCase())) {
String fileName = new File(uri).getName();
String content = handler.getAttributeValue( elem, "content" );
com.lowagie.text.Rectangle targetArea = checkLinkArea(c, box);
if (targetArea == null) {
return;
}
try {
if (!_attachments.contains(fileName)) {
byte[] fileBytes = Base64.getDecoder().decode(content.getBytes("UTF-8"));
PdfFileSpecification fs = PdfFileSpecification.fileEmbedded(_writer, null, fileName, fileBytes);
fs.addDescription(fileName, true);
_writer.addFileAttachment(fs);
_attachments.add(fileName);
}
targetArea.setBorder(0);
targetArea.setBorderWidth(0);
//This only works on Adobe Acrobat Reader
PdfAction action = PdfAction.javaScript(
"this.exportDataObject({cName:\"" + fileName + "\", nLaunch:2});",
_writer
);...
HTML
<body><div id='div1'><p><a href='test.png' data-fs-embed-file='true' content='iVBORw0KGgoAAAANSUhEU...'>open test.png file</a></p></div><div id='div2'><p><a href='test.pdf' data-fs-embed-file='true' content='JVBERi0xLjUNCiW1tbW1D...'>open test.pdf file</a></p></div><div id='div3'><p><a href='test.txt' data-fs-embed-file='true' content='VEVFRUVFRUVFRVNUIFRYVA=='>open test.txt file</a></p></div></body>
*base64 content truncated
Output
Greetings and I hope it can help others
just open it on new tab, add attribute target="_blank" in your anchor tag
Open attachment

Extract used CSS from a page

I need to extract the used CSS from a 19,000 line CSS file where 98.4% of it is unused (ouch). I know you can use Chrome Developer Tools to view the CSS Coverage, like so:
But it doesn't allow you to even jump to the green lines. Manually going through 19K lines just doesn't seem feasible.
Chrome Lighthouse doesn't seem to give you an option to see only the rules you need like Developer Tools used to, either.
I've tried Firefox's "CSS Usage" add-on (which a lot of sites recommend) but it requires FireBug, which itself isn't compatible in the current version of FireFox.
Can anyone think of a way to pull out just the CSS that's used somehow?
Hope this will help you
https://uncss-online.com/
just add html in left and css in right. Click ok btn then see magic
if there is any error in css then it will ask you to remove that error in that line number.
This is the easiest methode :)
After downloading the Coverage .json from Chrome (>= v73) [What's New In DevTools - Chrome 73].
You can extract the CSS with this node script:
$ node extractCSS.js ~/Desktop/Coverage-20190325T110812.json
https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css
https://d33wubrfki0l68.cloudfront.net/css/1bd6a34e1fcf409d29d1a960e6299893fca2e7b1/css/all.css
https://unpkg.com/bootstrap#4.1.3/dist/css/bootstrap.min.css
./final_css.css file saved
// extractCSS.js
const fs = require('fs');
let final_css_bytes = '';
let total_bytes = 0;
let used_bytes = 0;
const filename = process.argv[2];
const output = './final_css.css';
if (!filename) {
console.error('Missing filename to get coverage information from');
process.exit();
}
const file_coverage = fs.readFileSync(filename);
const css_coverage = JSON.parse(file_coverage);
for (const entry of css_coverage) {
if (!entry.url.endsWith('.css')) continue;
console.log(entry.url);
final_css_bytes += '# ' + entry.url + '\n\n';
total_bytes += entry.text.length;
for (const range of entry.ranges) {
used_bytes += range.end - range.start - 1;
final_css_bytes += entry.text.slice(range.start, range.end) + '\n';
}
final_css_bytes += '\n\n';
}
fs.writeFile(output, final_css_bytes, error => {
if (error) {
console.log('Error creating file:', error);
return;
}
console.log(output, 'file saved');
});
https://gist.github.com/gianpaj/a2f99e022e2c3f8abb9deecb47d572c4
Inspired by: https://blog.fullstacktraining.com/remove-unused-css-javascript-code-from-your-project/
I use PurifyCSS for some of my projects. Helps me to keep my CSS lightweight.
Dont' know about your project structure and workflow, but there are tons of tutorials out there:
https://webdesign.tutsplus.com/tutorials/remove-unnecessary-css-with-purifycss-and-grunt--cms-27726
https://survivejs.com/webpack/styling/eliminating-unused-css/
There are also some online solutions for getting rid of unused CSS, never tried though:
https://uncss-online.com/

Getting error when converting multipage fillable PDF to html form using Abcpdf

The exception thrown was " at WebSupergoo.ABCpdf10.Doc.Save(String path)
at GetHtmlFromUploadedPdfDocument(Nullable`1 pageNumber) in....." .
The uploaded pdffile contains barcodes and fillable fext fields .
Below is the code i used to convert pdf to html.
var filePaths= HttpContext.Current.Server.MapPath("~/PDF//");
byte[] bytes = File.ReadAllBytes(filePaths);
doc.Read(bytes);
if (pageNumber > 0)
{
doc.PageNumber = pageNumber.Value;
doc.RemapPages(pageNumber.ToString());
}
var pdfFile = "sample";
var htmlPath = HttpContext.Current.Server.MapPath("~/HTML/" + pdfFile + ".html");
doc.Encryption.CanChange = false;
doc.Encryption.CanEdit = false;
doc.Encryption.CanAssemble = false;
doc.Encryption.CanExtract = false;
doc.Encryption.CanFillForms = false;
doc.Save(htmlPath);
content = File.ReadAllText(htmlPath);
I know this is old post. But i faced similar issue.
I solved it eventually, it might help others.
In my case, folder under which I was saving the file was missing proper permission.
Please perform following task:
Right click on root folder where you are trying to save file.
Select Properties. Uncheck Read-only in attributes section.
Go to Security Tab. Select Edit > Add.
Key in "Everyone" in text box. Then Check Names > Ok.
Give "Everyone" Read, Write and Modify permission.

Webworker is not running

I have the following code:
var stressWorker = new Worker("./test/webworkers/worker.js");
stressWorker.onmessage = function(event){
alert(event.data);
};
stressWorker.onerror = function(event){
throw new Error(event.message + " (" + event.filename + ":" + event.lineno + ")");
};
worker.js:
onmessage = function(e){
postMessage("test");
}
The script finds the 'worker.js' file but it doesn't actually run it. What am I doing wrong?
PS. I'm hosting both scripts using wamp and I'm using chrome
worker.js won't do anything until it receives a message. I can't see where you are sending it a message. You need something like stressWorker.postMessage(...) somewhere.
Are you sure your browser supports this particular HTML5 feature?
This article has many ways to test for support of each feature. The test for Worker is
return !!window.Worker;
Edit: As I see it, there's either a problem with your code or it can't find the file. Your code looks a lot like this example except there the .js file code is like this, with the self:
self.onmessage = function(e) {
self.postMessage("Hello " + e.data);
};
It should be easy enough for you to try that and see if it's the missing piece here.
One main thing You should remember If you are running scripts on same origin and using chrome, you should start the chrome with the flag --allow-file-access-from-files or You should run app on local server.
See the code
var stressWorker = new Worker("../test/webworkers/worker.js");
stressWorker.onmessage = function(event){
alert(event.data);
};
stressWorker.postMessage("Hello there");
stressWorker.onerror = function(event){
throw new Error(event.message + " (" + event.filename + ":" + event.lineno + ")");
};
Now you will get The response from the worker. ".." I suspect path is wrong.