I am trying to get the source code(HTML code) of the current browser through a chrome extension. I was trying to store this HTML code in a string, but it doesn't seem to work.
http://jsfiddle.net/ufbxge08/2/
<head>
<style>
button {
height: 30px;
width: 100px;
outline: none;
}
</style>
</head>
<body>
<button id="bth1">Predict</button>
<script src="popup.js"></script>
<script src="jquery-2.0.3.js"></script>
<form>
<label id = 'mybtn1'></label>
</form>
JavaScript:
btn1.onclick = function scrapeThePage() {
// Keep this function isolated - it can only call methods you set up in content scripts
var htmlCode = document.documentElement.outerHTML;
var btn = document.getElementById("mybtn1");
btn.innerHTML = htmlCode;
console.log(htmlCode)
}
I expected the code to store the source code in a string but it doesn't seem to work.
If you want to show HTML code inside an HTML element you may need to set the text content (innerText), not the HTML content (innerHTML):
bth1.onclick = function scrapeThePage() {
// Keep this function isolated - it can only call methods you set up in content scripts
var htmlCode = document.documentElement.outerHTML;
var btn = document.getElementById("mybtn1");
btn.innerText = htmlCode;
}
http://jsfiddle.net/1jk94r50/
Related
I have looked for duplicate questions, however many refer to adding data to XML
please forgive me if I have missed something here but I need some help
so far I have this:
html page
<!DOCTYPE html>
<html>
<head>
<title>Template</title>
<script type="text/javascript" src="script/controlpanelAdmin.js"></script>
<script type="text/javascript" src="script/controlpanelModerator.js"></script>
<script type="text/javascript" src="script/jquery-1.12.0.js"></script>
<link rel="stylesheet" href="script/css.css" />
</head>
<body>
<fieldset id="control_panel">
<legend>Control Panel</legend>
</fieldset>
<p id="content"> Content </p>
</body>
</html>
controlpanelAdmin.js
window.onload = function() {
var controlpanel = document.getElementById("control_panel");
var para = document.createElement("p");
var att = document.createAttribute("admin");
var br = document.createElement("br");
var txt = document.createTextNode("Admin Control Panel");
controlpanel.appendChild(para);
para.setAttribute("id", att);
para.appendChild(txt);
para.appendChild(br);
}
controlpanelModerator.js
window.onload = function() {
var controlpanel = document.getElementById("control_panel");
var para = document.createElement("p");
var att = document.createAttribute("mod");
var br = document.createElement("br");
var txt = document.createTextNode("Moderator Control Panel");
controlpanel.appendChild(para);
para.setAttribute("id", att);
para.appendChild(txt);
para.appendChild(br);
}
When the page loads, 'Admin Control Panel' is written into the fieldset tag
but is then replaced by: 'Moderator Control Panel'
I cannot for the life of me think how to append both lines (and maybe other data as well) into one element
When the page loads, 'Admin Control Panel' is written into the fieldset tag but is then replaced by: 'Moderator Control Panel'
That can't happen. Admin Control Panel should never appear in the page.
script/controlpanelAdmin.js loads. It causes a value to be assigned to window.onload.
script/controlpanelModerator.js loads. It causes that value to be overwritten with a new one.
The page finishes loading
The load event fires
The function defined in script/controlpanelModerator.js is called
Don't assign values to window.onload. Use addEventListener instead.
addEventListener("load", function () { ... });
You've got two onload functions competing. Can you merge them into one function?
I have a js rendered in HTML which would give a preview of the form. The code is functioning correctly but it gives me the output on the same page rather i want to open it in a pop-up window. I have tried using window.open () with no luck. Could you please help me out in how i can use window.open() for the below. The button ID is preview. When the button is clicked it executes a function similar to below
$("#preview").click(function() {
$("#formpreview").delete();
var fieldSet = ...................});
You can populate the html in the child window using the below example:
HTML
<!DOCTYPE Html />
<html>
<head>
<title></title>
</head>
<body>
<input type="button" id="launch" value="Launch Child Window"/>
<script type="text/javascript" src="theJS.js"></script>
</body>
</html>
JavaScript
var btnLaunch = document.getElementById("launch");
btnLaunch.onclick = function () {
var childWindow = window.open("", "", "height=500, width=500");
var html = "";
var theVariable = "Conent in Child Window";
html += "<p>" + theVariable + "</p>";
childWindow.document.body.innerHTML = html;
}
Store the popup as a variable, then set the popup's HTML to whatever you need.
$("#preview").click(function() {
var myWindow = window.open("", "Popup", "width=300, height=500");
myWindow.document.write("<html>This is where your content goes</html>");
});
I am trying to build a HTML, CSS and jQuery (not just JavaScript) editor, and show the rendered content in an iFrame. Although adding HTML, CSS part is easy, I am unable to execute the JavaScript part.
var html = ""; // HTML code
var content = $("#preview").contents().find("body"); // iframe id is 'preview'
content.html(html);
var cssLink = "<style>" + csVal + "</style>"; // cssVal contains css code
var head = $("#preview").contents().find("head");
head.append(cssLink);
var js ='<script>'+jsEditor()+'<\/script>' ;
// following part is not working
var content = $('#preview').contents();
$content.find('head').append('<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"><\/script>' );
$content.find('body').append(js );
I am able to execute to core JavaScript using window.eval(), however it is not working for any JS library included, e.g. jQuery etc.
I think your only problem here is your variable naming:
var content = $('#preview').contents();
$content.find('head').append('<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"><\/script>' );
$content.find('body').append(js );
should be ($content ==> content)
var content = $('#preview').contents();
content.find('head').append('<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"><\/script>' );
content.find('body').append(js );
I modified your script slightly but only to provide some pre-canned values for html, csVal and a result from jsEditor().
This worked for me in Chrome, Safari & Firefox running off a server on localhost:
HTML:
<html>
<head>
</head>
<body>
<div>Look at your new iFrame</div>
<iframe id="preview"></iframe>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</body>
</html>
Code (also in the html body):
$(document).ready(function() {
var html = "<div>Hello from iframe</div>"; // HTML code
var content = $("#preview").contents().find("body"); // iframe id is 'preview'
content.html(html);
var csVal = "div { color: red; font-size: 40px;}";
var cssLink = "<style>" + csVal + "</style>"; // cssVal contains css code
var head = $("#preview").contents().find("head");
head.append(cssLink);
var jsCode = "alert('you are in the iframe')";
var js ='<script>'+jsCode+'<\/script>' ;
// following part is not working
var content = $('#preview').contents();
content.find('head').append('<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"><\/script>' );
content.find('body').append(js );
});
Resulting source in the iFrame:
<html>
<head>
<style>
div {
color: red;
font-size: 40px;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
</head>
<body>
<div>Hello from iframe</div>
<script>
alert('you are in the iframe')
</script>
</body>
</html>
This problem is only happening in IE (at least 8 and 9). After an element is dynamically added to the DOM, the contents of an embedded iframe are lost when the page is reentered with a BACK/FORWARD key. Just two small HTML files will reproduce the issue.
The first file is iframe.htm:
<!DOCTYPE html>
<html>
<head>
<title>IE iframe bug</title>
<script type="text/javascript">
function mytrace(msg) {
var t = document.createTextNode(msg);
var b = document.createElement('br');
var d = document.getElementById("trace_output")
d.appendChild(t);
d.appendChild(b); /// will work if commented
}
function submitListing() {
mytrace('submitListing()');
var doc = document.getElementById("output_iframe")
.contentWindow.document;
var d = new Date;
doc.location.replace('report.htm?invalidateCache=' + d.getTime());
//mytrace('submitListing(): out');
}
</script>
</head>
<body>
<div id="trace_output"><br /></div>
<input type="button" onclick="submitListing();" value="Run" /><br />
<iframe id="output_iframe" src=""></iframe>
</body>
</html>
The second file is report.htm:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
LINK
</body>
</html>
Steps to recreate the issue (BACK KEY)
Place above content in two files
Browse the iframe.htm file
Press the Run button to load report.htm in the iframe
Click on the LINK link to load a different page
Press the browser BACK button to returned to the "cached" (lmao) page
iframe contents are gone!!!! (only in IE-- safari, chrome, firefox retain the contents)
Also..(FORWARD KEY)
Browse to an arbitrary page (for history, http://www.google.com works)
Load iframe.htm into the same tab
Press the Run button to load report.htm in the iframe
Press the browser BACK button to return to the first page
Press the browser FORWARD button to return to iframe.htm
iframe contents are gone again!!
Now comment out the line:
d.appendChild(b)
That one change allows everything to work in IE. However, my solution needs to make those kinds of DOM manipulations (heavy jQuery/AJAX app) AND be able to restore the iframe across browser BACK/FORWARD actions.
It seems that I will have to remember the contents of the iframe so that I can restore it when the page is accessed with the BACK/FORWARD keys. I'm not thrilled with this because sometimes the iframe content will be quite large and it could chew up a bit of memory and time to make another copy of the embedded document for the restore. I would love to hear some other ideas about how I could approach this. Thanks in advance.
EDIT
The following replacement to iframe.htm will work around the problem with IE. I'm going to rewrite this using jQuery and add some more logic to restore the scroll positions. I had hoped for something more elegant, but this is doing the job.
<!DOCTYPE html>
<html>
<head>
<title>IE iframe bug</title>
<script type="text/javascript">
function myTrace(msg) {
var t = document.createTextNode(msg);
var b = document.createElement('br');
var d = document.getElementById("trace_output")
d.appendChild(t);
d.appendChild(b);
}
var make_backup ="false";
function submitListing() {
make_backup = "true";
myTrace('submitListing()');
var doc = document.getElementById("output_iframe").contentWindow.document;
var d = new Date;
doc.location.replace('report.htm?invalidateCache=' + d.getTime());
//myTrace('submitListing(): out');
}
function iframe_load() {
myTrace("iframe loaded, is_cached=" + document.getElementById("is_cached").value);
if (make_backup == "true") { // only when submitting
var htm, doc;
make_backup = "false"
doc = document.getElementById("output_iframe").contentWindow.document;
htm = doc.documentElement.innerHTML;
document.getElementById("iframe_backup").value = htmlEscape(htm);
}
}
function bodyLoaded() {
var is_cached = document.getElementById("is_cached");
if (is_cached.value == "false") { // initial page load
is_cached.value = "true";
}
else { // BACK or FORWARD, restore DOM where needed
var htm;
htm = htmlUnescape(document.getElementById("iframe_backup").value);
var doc;
doc = document.getElementById("output_iframe").contentWindow.document;
doc.open();
doc.writeln(htm);
doc.close();
}
}
function htmlEscape(str) {
return String(str).replace(/&/g, '&').replace(/"/g, '"')
.replace(/'/g, ''').replace(/</g, '<').replace(/>/g, '>');
}
function htmlUnescape(str) {
return String(str).replace(/&/g,'&').replace(/"/g,'"')
.replace(/'/g,"'").replace(/</g,'<').replace(/>/g,'>');
}
</script>
</head>
<body onload="bodyLoaded();">
<div id="trace_output" style="height: 300px; border-width:1; background-color: Silver"><br></div>
<input id="is_cached" type="hidden" value="false">
<input id="iframe_backup" type="hidden">
<input type="button" onclick="submitListing();" value="Run"><br>
<iframe id="output_iframe" src="" onload="iframe_load();"></iframe>
</body>
</html>
EDIT 2
Rewritten with jQuery:
<!DOCTYPE html>
<html>
<head>
<title>IE iframe workaround2</title>
<script type="text/javascript" src="Scripts/jquery-1.7.1.js"></script>
<script type="text/javascript">
var make_backup = "false";
$(document).ready(function () {
myTrace('document ready()');
var is_cached = $("#is_cached");
if (is_cached.val() == "false") { // initial page load
is_cached.val("true");
}
else { // BACK or FORWARD, restore DOM where needed
if ($.browser.msie) { // IE loses iframe content; restore
var htm = htmlUnescape($("#iframe_backup").val());
var doc = $("#output_iframe")[0].contentWindow.document;
doc.open();
doc.writeln(htm);
doc.close();
myTrace('iframe contents restored');
}
}
$('#output_iframe').load(function () {
myTrace("iframe_loaded");
if (make_backup == "true") { // only when submitting
make_backup = "false"
if ($.browser.msie) {
var doc = $("#output_iframe")[0].contentWindow.document;
var htm = doc.documentElement.innerHTML;
$("#iframe_backup").val(htmlEscape(htm));
myTrace('iframe contents backed up');
}
}
});
$('#submit_listing').click(function () {
make_backup = "true";
myTrace('submitListing()');
var doc = $("#output_iframe")[0].contentWindow.document;
var d = new Date;
doc.location.replace('report.htm?invalidateCache='+d.getTime());
});
});
function myTrace(msg) {
$('#trace_output').append(msg + '<br>');
}
function htmlEscape(str) {
return String(str).replace(/&/g, '&').replace(/"/g, '"')
.replace(/'/g, ''').replace(/</g, '<').replace(/>/g, '>');
}
function htmlUnescape(str) {
return String(str).replace(/&/g,'&').replace(/"/g,'"')
.replace(/'/g,"'").replace(/</g,'<').replace(/>/g,'>');
}
</script>
</head>
<body>
<div id="trace_output"
style="height: 300px; border-width:1; background-color: Silver">
<br></div>
<div style="display: block;">
<input id="is_cached" type="text" value="false">
<input id="iframe_backup" type="text" type="hidden"></div>
<input id="submit_listing" type="button" value="Run"><br>
<iframe id="output_iframe" src=""></iframe>
</body>
</html>
I'm opening a popup using popup = window.open(....) and then trying to insert some html into a div in the popup.
popup.document.getElementById('div-content').innerHTML = "hello world"; doesn't do anything however, popup.document.getElementById('the-field').value = "Hello There"; changes the content of a field with an id="the-field".
Any idea why one is working but not the other? How can i replace the content of the div?
hope you can help.
EDIT:
the popup
<!DOCTYPE html>
<html>
<head>
<title>Report</title>
<meta charset="utf-8">
</head>
<body>
<header>
</header>
<div id="div-content"></div>
<div id="report-container">
<input type="text" id="the-field" name="the_field"/>
</div>
<footer>
</footer>
</body>
</html>
the code
function reportComplete(report_content)
{
var popup;
var template_path;
template_path = base_url + "application/views/secure/reports_preview.php";
popup = window.open(template_path, "Report", "scrollbars=yes ,resizable=yes");
popup.document.getElementById('the-field').value = "Hello There"; // this works
popup.document.getElementById('div-content').innerHTML = "hello world";
}
...or simply:
<script type="text/javascript">
function reportComplete(report_content)
{
var popup;
var template_path;
template_path = base_url + "application/views/secure/reports_preview.php";
popup = window.open(template_path, "Report", "scrollbars=yes,resizable=yes");
popup.window.onload = function() {
popup.document.getElementById('the-field').value = "Hello There";
popup.document.getElementById('div-content').innerHTML = "hello world";
}
}
</script>
I think the problem here is that the document in the popup windows hasn't finished loading when you try to access a part of it. On my machine, neither of the divs can be accessed with the provided code.
If the content you want to insert is fixed, then just do all these changes on the popup page itself so that you can make it happen only when the document is completely loaded. If you need to send some dynamic contents, the easiest approach may be using query strings.
UPDATE:
There is a way to fire up DOM manipulation function only when the popup finishes loading. First, you need a callback function on the main window, and put all the DOM manipulation code there:
window.callback = function(doc) {
doc.getElementById('the-field').value = "Hello there";
doc.getElementById('div-content').innerHTML = "Hello world";
}
Then, simply bind a function call to the body onload event on the popup window:
<script type="text/javascript">
function loaded() {
window.opener.callback(document);
}
</script>
<body onload="loaded();"><!-- body content --></body>