Add content to a new open window - javascript

I don't know how to solve this issue, I've trying reading many post but no one answer to it.
I need to open a new window with a page already coded (inside the same domain) and add some content.
The problem is that if I use OpenWindow.write() the page is not loaded yet or it overrides everything and only the code added through write appears.
var OpenWindow = window.open('mypage.html','_blank','width=335,height=330,resizable=1');
OpenWindow.document.write(output);
output is the code I need to append.
I need it to work at least on Firefox, IE and GC.
It is not a problem if I need to use JQuery.

When You want to open new tab/window (depends on Your browser configuration defaults):
output = 'Hello, World!';
window.open().document.write(output);
When output is an Object and You want get JSON, for example (also can generate any type of document, even image encoded in Base64)
output = ({a:1,b:'2'});
window.open('data:application/json;' + (window.btoa?'base64,'+btoa(JSON.stringify(output)):JSON.stringify(output)));
Update
Google Chrome (60.0.3112.90) block this code:
Not allowed to navigate top frame to data URL: data:application/json;base64,eyJhIjoxLCJiIjoiMiJ9
When You want to append some data to existing page
output = '<h1>Hello, World!</h1>';
window.open('output.html').document.body.innerHTML += output;
output = 'Hello, World!';
window.open('about:blank').document.body.innerText += output;

in parent.html:
<script type="text/javascript">
$(document).ready(function () {
var output = "data";
var OpenWindow = window.open("child.html", "mywin", '');
OpenWindow.dataFromParent = output; // dataFromParent is a variable in child.html
OpenWindow.init();
});
</script>
in child.html:
<script type="text/javascript">
var dataFromParent;
function init() {
document.write(dataFromParent);
}
</script>

Here is what you can try
Write a function say init() inside mypage.html that do the html thing ( append or what ever)
instead of OpenWindow.document.write(output); call OpenWindow.init() when the dom is ready
So the parent window will have
OpenWindow.onload = function(){
OpenWindow.init('test');
}
and in the child
function init(txt){
$('#test').text(txt);
}

When you call document.write after a page has loaded it will eliminate all content and replace it with the parameter you provide. Instead use DOM methods to add content, for example:
var OpenWindow = window.open('mypage.html','_blank','width=335,height=330,resizable=1');
var text = document.createTextNode('hi');
OpenWindow.document.body.appendChild(text);
If you want to use jQuery you get some better APIs to deal with. For example:
var OpenWindow = window.open('mypage.html','_blank','width=335,height=330,resizable=1');
$(OpenWindow.document.body).append('<p>hi</p>');
If you need the code to run after the new window's DOM is ready try:
var OpenWindow = window.open('mypage.html','_blank','width=335,height=330,resizable=1');
$(OpenWindow.document.body).ready(function() {
$(OpenWindow.document.body).append('<p>hi</p>');
});

If you want to open a page or window with sending data POST or GET method you can use a code like this:
$.ajax({
type: "get", // or post method, your choice
url: yourFileForInclude.php, // any url in same origin
data: data, // data if you need send some data to page
success: function(msg){
console.log(msg); // for checking
window.open('about:blank').document.body.innerHTML = msg;
}
});

it is even more simple!
Just put the code below in between the <head> </head> of your code and all of your links will open in a new window:
<base target="_blank">

Related

JQuery Using passed parameter value to initialize a page via $(document).ready

I am trying to access or make a parameter value which was passed via an <a> visible within another javascript file. I can't figure out how to go about it.
I have the ff. line of code which goes to a new page: student_learn_topiclink.php everytime the link is clicked
var topicLink = $('<a>' + topicTitle+ '</a>').addClass('topic_link').attr('href','view/student_learn_topiclink.php?topicId=' + topicId).attr('target','_blank');
This is what shows in the address bar after clicking the topicLink
http://localhost/cai/view/student_learn_topiclink.php?topicId=5
I want to use the value 5 in student_learn_topiclink page's JS file.
How can I expose or make the topicId = 5 visible in student_learn_topiclink JS file?
In student_learn_topiclink.js, I'd like to do something like this,
$(document).ready(function(){
alert(topicId);
});
See this thread about retrieving URL parameters with javascript. For your specific example, try the following:
var url_string = window.location.href;
var url = new URL(url_string);
var topicId = url.searchParams.get("topicId");
console.log(topicId);
Example fiddle: http://jsfiddle.net/craftman32/yxrvbcun/1/
You can use like this :
var topicId = window.location.search.split('topicId=')[1];
console.log(topicId);

Running Javascript in new window.open

I'm running this function to open a new window.
function htmlNewWindow(id) {
var html = $(id).html();
var newWindow = window.open('');
newWindow.document.body.innerHTML = '<html><head><title>Hi</title> <script src="js/myScript.js"></script> </head>' + html;
}
This successfully creates a new window with the HTML in it. I have a bunch of HTML tags which when clicked run a function called Foo1. I've tried printing the entire function of Foo1 to the new HTML document, and tried putting Foo1 inside myScript.js. I see both Foo1 inside a script tag in the new window, and but neither are loaded since they are just written to the new page as HTML.
Scripts added with .innerHTML aren't executed. You need to create a script node and append it to the window's DOM.
$("#button").click(newWindow);
function newWindow(id) {
var html = $(id).html();
var win = window.open('');
win.document.head.innerHTML = '<title>Hi</title></head>';
win.document.body.innerHTML = '<body>' + html + '</body>';
var script = document.createElement('script');
script.src = 'js/myScript.js';
win.document.head.appendChild(script);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="button">Click me</button>
This doesn't run in Stack Snippet's sandbox, here's a working jsfiddle.
Try this:
var newWindow = window.open('');
newWindow.document.createElement('script');
script.src = 'js/myScript.js';
newWindow.document.head.appendChild(script);
Just in case someone has this to be done in a link. Do the following:
Link
This opens a new window with that URL, it set the focus to that windows, and as soon as the 'load' event is triggered, it executes the code in the function. It only works with a page in the same domain.
Hope this helps ⬆✌.
Cheers 👍
Here's how you create, and then append a script file within a new window:
var fileref = document.createElement('script');
//creates script in current document
fileref.setAttribute("type", "text/javascript")
//set it to JS by "type"
fileref.setAttribute("src", filename)
//set your "src=yourFile_href_Here.js"
//Then create your newWindow as you did above, but slightly updated
//Create your function which will consume the "fileref" argument
function htmlNewWindow(fileref) {
var newWindow = window.open('');
newWindow.document.getElementsByTagName("head")[0].appendChild(fileref);
}; //right now the function is made but you still have to execute it
//Execute your function, and pass it the variable "fileref" that you set above.
htmlNewWindow(fileref);
//Within this edit you will append the head element
//with your newly created script(or any other parameterized argument)
/* Replace your filename to pass any other script */
NOTE - Opening a page residing on a different domain, if not specifically allowed, will reject instances of this due to CORS(https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS)
It's not a safe practice to be sending your scripts into other people's pages or allowing them in your own if your domain hasn't sent them. Also, depending on your server/technology stack you may need to configure your *-origin settings within your backend stack. See here: (https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy)

Get script content [duplicate]

If I have a script tag like this:
<script
id = "myscript"
src = "http://www.example.com/script.js"
type = "text/javascript">
</script>
I would like to get the content of the "script.js" file. I'm thinking about something like document.getElementById("myscript").text but it doesn't work in this case.
tl;dr script tags are not subject to CORS and same-origin-policy and therefore javascript/DOM cannot offer access to the text content of the resource loaded via a <script> tag, or it would break same-origin-policy.
long version:
Most of the other answers (and the accepted answer) indicate correctly that the "correct" way to get the text content of a javascript file inserted via a <script> loaded into the page, is using an XMLHttpRequest to perform another seperate additional request for the resource indicated in the scripts src property, something which the short javascript code below will demonstrate. I however found that the other answers did not address the point why to get the javascript files text content, which is that allowing to access content of the file included via the <script src=[url]></script> would break the CORS policies, e.g. modern browsers prevent the XHR of resources that do not provide the Access-Control-Allow-Origin header, hence browsers do not allow any other way than those subject to CORS, to get the content.
With the following code (as mentioned in the other questions "use XHR/AJAX") it is possible to do another request for all not inline script tags in the document.
function printScriptTextContent(script)
{
var xhr = new XMLHttpRequest();
xhr.open("GET",script.src)
xhr.onreadystatechange = function () {
if(xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
console.log("the script text content is",xhr.responseText);
}
};
xhr.send();
}
Array.prototype.slice.call(document.querySelectorAll("script[src]")).forEach(printScriptTextContent);
and so I will not repeat that, but instead would like to add via this answer upon the aspect why itthat
Do you want to get the contents of the file http://www.example.com/script.js? If so, you could turn to AJAX methods to fetch its content, assuming it resides on the same server as the page itself.
Update: HTML Imports are now deprecated (alternatives).
---
I know it's a little late but some browsers support the tag LINK rel="import" property.
http://www.html5rocks.com/en/tutorials/webcomponents/imports/
<link rel="import" href="/path/to/imports/stuff.html">
For the rest, ajax is still the preferred way.
I don't think the contents will be available via the DOM. You could get the value of the src attribute and use AJAX to request the file from the server.
yes, Ajax is the way to do it, as in accepted answer. If you get down to the details, there are many pitfalls. If you use jQuery.load(...), the wrong content type is assumed (html instead of application/javascript), which can mess things up by putting unwanted <br> into your (scriptNode).innerText, and things like that. Then, if you use jQuery.getScript(...), the downloaded script is immediately executed, which might not be what you want (might screw up the order in which you want to load the files, in case you have several of those.)
I found it best to use jQuery.ajax with dataType: "text"
I used this Ajax technique in a project with a frameset, where the frameset and/or several frames need the same JavaScript, in order to avoid having the server send that JavaScript multiple times.
Here is code, tested and working:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">
<html>
<head>
<script id="scriptData">
var scriptData = [
{ name: "foo" , url: "path/to/foo" },
{ name: "bar" , url: "path/to/bar" }
];
</script>
<script id="scriptLoader">
var LOADER = {
loadedCount: 0,
toBeLoadedCount: 0,
load_jQuery: function (){
var jqNode = document.createElement("script");
jqNode.setAttribute("src", "/path/to/jquery");
jqNode.setAttribute("onload", "LOADER.loadScripts();");
jqNode.setAttribute("id", "jquery");
document.head.appendChild(jqNode);
},
loadScripts: function (){
var scriptDataLookup = this.scriptDataLookup = {};
var scriptNodes = this.scriptNodes = {};
var scriptNodesArr = this.scriptNodesArr = [];
for (var j=0; j<scriptData.length; j++){
var theEntry = scriptData[j];
scriptDataLookup[theEntry.name] = theEntry;
}
//console.log(JSON.stringify(scriptDataLookup, null, 4));
for (var i=0; i<scriptData.length; i++){
var entry = scriptData[i];
var name = entry.name;
var theURL = entry.url;
this.toBeLoadedCount++;
var node = document.createElement("script");
node.setAttribute("id", name);
scriptNodes[name] = node;
scriptNodesArr.push(node);
jQuery.ajax({
method : "GET",
url : theURL,
dataType : "text"
}).done(this.makeHandler(name, node)).fail(this.makeFailHandler(name, node));
}
},
makeFailHandler: function(name, node){
var THIS = this;
return function(xhr, errorName, errorMessage){
console.log(name, "FAIL");
console.log(xhr);
console.log(errorName);
console.log(errorMessage);
debugger;
}
},
makeHandler: function(name, node){
var THIS = this;
return function (fileContents, status, xhr){
THIS.loadedCount++;
//console.log("loaded", name, "content length", fileContents.length, "status", status);
//console.log("loaded:", THIS.loadedCount, "/", THIS.toBeLoadedCount);
THIS.scriptDataLookup[name].fileContents = fileContents;
if (THIS.loadedCount >= THIS.toBeLoadedCount){
THIS.allScriptsLoaded();
}
}
},
allScriptsLoaded: function(){
for (var i=0; i<this.scriptNodesArr.length; i++){
var scriptNode = this.scriptNodesArr[i];
var name = scriptNode.id;
var data = this.scriptDataLookup[name];
var fileContents = data.fileContents;
var textNode = document.createTextNode(fileContents);
scriptNode.appendChild(textNode);
document.head.appendChild(scriptNode); // execution is here
//console.log(scriptNode);
}
// call code to make the frames here
}
};
</script>
</head>
<frameset rows="200pixels,*" onload="LOADER.load_jQuery();">
<frame src="about:blank"></frame>
<frame src="about:blank"></frame>
</frameset>
</html>
related question
.text did get you contents of the tag, it's just that you have nothing between your open tag and your end tag. You can get the src attribute of the element using .src, and then if you want to get the javascript file you would follow the link and make an ajax request for it.
In a comment to my previous answer:
I want to store the content of the script so that I can cache it and use it directly some time later without having to fetch it from the external web server (not on the same server as the page)
In that case you're better off using a server side script to fetch and cache the script file. Depending on your server setup you could just wget the file (periodically via cron if you expect it to change) or do something similar with a small script inthe language of your choice.
if you want the contents of the src attribute, you would have to do an ajax request and look at the responsetext. If you where to have the js between and you could access it through innerHTML.
This might be of interest: http://ejohn.org/blog/degrading-script-tags/
I had a same issue, so i solve it this way:
The js file contains something like
window.someVarForReturn = `content for return`
On html
<script src="file.js"></script>
<script>console.log(someVarForReturn)</script>
In my case the content was html template. So i did something like this:
On js file
window.someVarForReturn = `<did>My template</div>`
On html
<script src="file.js"></script>
<script>
new DOMParser().parseFromString(someVarForReturn, 'text/html').body.children[0]
</script>
You cannot directly get what browser loaded as the content of your specific script tag (security hazard);
But
you can request the same resource (src) again ( which will succeed immediately due to cache ) and read it's text:
const scriptSrc = document.querySelector('script#yours').src;
// re-request the same location
const scriptContent = await fetch(scriptSrc).then((res) => res.text());
If you're looking to access the attributes of the <script> tag rather than the contents of script.js, then XPath may well be what you're after.
It will allow you to get each of the script attributes.
If it's the example.js file contents you're after, then you can fire off an AJAX request to fetch it.
It's funny but we can't, we have to fetch them again over the internet.
Likely the browser will read his cache, but a ping is still sent to verify the content-length.
[...document.scripts].forEach((script) => {
fetch(script.src)
.then((response) => response.text() )
.then((source) => console.log(source) )
})
Using 2008-style DOM-binding it would rather be:
document.getElementById('myscript').getAttribute("src");
document.getElementById('myscript').getAttribute("type");
You want to use the innerHTML property to get the contents of the script tag:
document.getElementById("myscript").innerHTML
But as #olle said in another answer you probably want to have a read of:
http://ejohn.org/blog/degrading-script-tags/
If a src attribute is provided, user agents are required to ignore the content of the element, if you need to access it from the external script, then you are probably doing something wrong.
Update: I see you've added a comment to the effect that you want to cache the script and use it later. To what end? Assuming your HTTP is cache friendly, then your caching needs are likely taken care of by the browser already.
I'd suggest the answer to this question is using the "innerHTML" property of the DOM element. Certainly, if the script has loaded, you do not need to make an Ajax call to get it.
So Sugendran should be correct (not sure why he was voted down without explanation).
var scriptContent = document.getElementById("myscript").innerHTML;
The innerHTML property of the script element should give you the scripts content as a string provided the script element is:
an inline script, or
that the script has loaded (if using the src attribute)
olle also gives the answer, but I think it got 'muddled' by his suggesting it needs to be loaded through ajax first, and i think he meant "inline" instead of between.
if you where to have the js between and you could access it through innerHTML.
Regarding the usefulness of this technique:
I've looked to use this technique for client side error logging (of javascript exceptions) after getting "undefined variables" which aren't contained within my own scripts (such as badly injected scripts from toolbars or extensions) - so I don't think it's such a way out idea.
Not sure why you would need to do this?
Another way round would be to hold the script in a hidden element somewhere and use Eval to run it. You could then query the objects innerHtml property.

Firefox Add-on: get document from a tab

I was just trying to get the document of a tab and read information from it, but if I try to read the information on the Add-on-side I get an error "doc.getElementById is not a function". In the content-script it works fine. So is there a problem with passing whole objects through self.port?
var tabs = require('sdk/tabs');
var myTab;
var myScript = "self.port.on('getDocument', function() {" +
" var doc = window.document;" +
" console.log(doc.getElementById('lga').style.height);" +
" self.port.emit('answer', doc);" +
"})";
for each (var tab in tabs) {
if (tab.url == "https://www.google.com/") {
myTab = tab;
}
}
worker = myTab.attach({
contentScript: myScript
});
worker.port.emit("getDocument");
worker.port.on("answer", function(doc) {
console.log(doc.getElementById('lga').style.height);
});
You can only pass values via a message that could be serialized to JSON. doc, being a document, cannot be passed.
In your message, you could pass the actual value of the style instead:
self.port.emit('answer', doc.getElementById('lga').style.height);
Rather than try to import the document into main.js, create a new Javascript file in the data folder, ContentScript.js. Inject it with contentScriptFile into the page like so:
worker = myTab.attach({
contentScriptFile: require('sdk/self').data.url('ContentScript.js')
});
Meanwhile, in ContentScript.js
var doc = window.document;
//Now have your way with the document
Then if you ever need any variables in main.js, do what #nmaier said.
I realize that this may be obvious, but this is the intended behaviour, and it means you don't have to write a script as a string and provides more detailed logging.

Grab url variable from inside an iframe

I have no control over anything apart from the iframe.
my form sits in the iframe and I want to grab a variable that comes from the parent link.
Not sure if its poss as the parent url is a different domain.
I cant give live urls, but for example:
www.theredomain.com?ref=variable is the parent url
I need to grab the variable of 'ref' from my iframe which is on a different domain. I have tried the below but it didnt seem to do anything.
<script language="javascript">
function getUrlVars() {
var vars = {};
var parts = window.parent.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
vars[key] = value;
});
return vars;
}
var first = getUrlVars()["ref"];
alert(first);
</script>
You can't access the parent from your iframe if it's in another domain.
One way of sending data between two iframes that are not on the same domain and if you have access to both of these to extend them is to use postMessage
it is fairly straight forward. On one side you implement a bit of js as an event listener which recognises the url it is coming from, on the other, you use the .postMessage method to send to that parent iframe. Check the browser support as well if it applies to you.
Thanks for the input guys - finally resolved it. I used the below function to break out the variable from the referrer url
<script>
function getUrlVars() {
var vars = {};
var parts = document.referrer.replace(/[?&]+([^=&]+)=([^&]*)/gi, function (m,key,value) {
vars[key] = value;
});
return vars;
}
</script>
Then put it into my form like
<script>
$("#submit").click(function() {
var first = getUrlVars()["ref"];
$(".referer").val(first);
});
<script>

Categories

Resources