Any idea why the piece of code below does not add the script element to the DOM?
var code = "<script></script>";
$("#someElement").append(code);
The Good News is:
It's 100% working.
Just add something inside the script tag such as alert('voila!');. The right question you might want to ask perhaps, "Why didn't I see it in the DOM?".
Karl Swedberg has made a nice explanation to visitor's comment in jQuery API site. I don't want to repeat all his words, you can read directly there here (I found it hard to navigate through the comments there).
All of jQuery's insertion methods use
a domManip function internally to
clean/process elements before and
after they are inserted into the DOM.
One of the things the domManip
function does is pull out any script
elements about to be inserted and run
them through an "evalScript routine"
rather than inject them with the rest
of the DOM fragment. It inserts the
scripts separately, evaluates them,
and then removes them from the DOM.
I believe that one of the reasons jQuery
does this is to avoid "Permission
Denied" errors that can occur in
Internet Explorer when inserting
scripts under certain circumstances.
It also avoids repeatedly
inserting/evaluating the same script
(which could potentially cause
problems) if it is within a containing
element that you are inserting and
then moving around the DOM.
The next thing is, I'll summarize what's the bad news by using .append() function to add a script.
And The Bad News is..
You can't debug your code.
I'm not joking, even if you add debugger; keyword between the line you want to set as breakpoint, you'll be end up getting only the call stack of the object without seeing the breakpoint on the source code, (not to mention that this keyword only works in webkit browser, all other major browsers seems to omit this keyword).
If you fully understand what your code does, than this will be a minor drawback. But if you don't, you will end up adding a debugger; keyword all over the place just to find out what's wrong with your (or my) code. Anyway, there's an alternative, don't forget that javascript can natively manipulate HTML DOM.
Workaround.
Use javascript (not jQuery) to manipulate HTML DOM
If you don't want to lose debugging capability, than you can use javascript native HTML DOM manipulation. Consider this example:
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "path/to/your/javascript.js"; // use this for linked script
script.text = "alert('voila!');" // use this for inline script
document.body.appendChild(script);
There it is, just like the old days isn't it. And don't forget to clean things up whether in the DOM or in the memory for all object that's referenced and not needed anymore to prevent memory leaks. You can consider this code to clean things up:
document.body.removechild(document.body.lastChild);
delete UnusedReferencedObjects; // replace UnusedReferencedObject with any object you created in the script you load.
The drawback from this workaround is that you may accidentally add a duplicate script, and that's bad. From here you can slightly mimic .append() function by adding an object verification before adding, and removing the script from the DOM right after it was added. Consider this example:
function AddScript(url, object){
if (object != null){
// add script
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "path/to/your/javascript.js";
document.body.appendChild(script);
// remove from the dom
document.body.removeChild(document.body.lastChild);
return true;
} else {
return false;
};
};
function DeleteObject(UnusedReferencedObjects) {
delete UnusedReferencedObjects;
}
This way, you can add script with debugging capability while safe from script duplicity. This is just a prototype, you can expand for whatever you want it to be. I have been using this approach and quite satisfied with this. Sure enough I will never use jQuery .append() to add a script.
I've seen issues where some browsers don't respect some changes when you do them directly (by which I mean creating the HTML from text like you're trying with the script tag), but when you do them with built-in commands things go better. Try this:
var script = document.createElement( 'script' );
script.type = 'text/javascript';
script.src = url;
$("#someElement").append( script );
From: JSON for jQuery
It is possible to dynamically load a JavaScript file using the jQuery function getScript
$.getScript('http://www.whatever.com/shareprice/shareprice.js', function() {
Display.sharePrice();
});
Now the external script will be called, and if it cannot be loaded it will gracefully degrade.
What do you mean "not working"?
jQuery detects that you're trying to create a SCRIPT element and will automatically run the contents of the element within the global context. Are you telling me that this doesn't work for you? -
$('#someElement').append('<script>alert("WORKING");</script>');
Edit: If you're not seeing the SCRIPT element in the DOM (in Firebug for example) after you run the command that's because jQuery, like I said, will run the code and then will delete the SCRIPT element - I believe that SCRIPT elements are always appended to the body... but anyway - placement has absolutely no bearing on code execution in this situation.
This works:
$('body').append($("<script>alert('Hi!');<\/script>")[0]);
It seems like jQuery is doing something clever with scripts so you need to append the html element rather than jQuery object.
Try this may be helpful:
var fileref=document.createElement('script');
fileref.setAttribute("type","text/javascript");
fileref.setAttribute("src","scriptAnalytics.js");
document.getElementsByTagName("head")[0].appendChild(fileref);
I want to do the same thing but to append a script tag in other frame!
var url = 'library.js';
var script = window.parent.frames[1].document.createElement('script' );
script.type = 'text/javascript';
script.src = url;
$('head',window.parent.frames[1].document).append(script);
<script>
...
...jQuery("<script></script>")...
...
</script>
The </script> within the string literal terminates the entire script, to avoid that "</scr" + "ipt>" can be used instead.
Adding the sourceURL in the script file helped as mentioned in this page:
https://blog.getfirebug.com/2009/08/11/give-your-eval-a-name-with-sourceurl/
In the script file, add a statement with sourceURL like "//# sourceURL=foo.js"
Load the script using jQuery $.getScript() and the script will be available in "sources" tab in chrome dev tools
Your script is executing , you just can't use document.write from it. Use an alert to test it and avoid using document.write. The statements of your js file with document.write will not be executed and the rest of the function will be executed.
This is what I think is the best solution. Google Analytics is injected this way.
var (function(){
var p="https:" == document.location.protocol ? "https://" : "http://";
d=document,
g=d.createElement('script'),
s=d.getElementsByTagName('script')[0];
g.type='text/javascript';
g.src=p+'url-to-your-script.js';
s.parentNode.insertBefore(g,s); })();
You don't need jQuery to create a Script DOM Element. It can be done with vanilla ES6 like so:
const script = "console.log('Did it work?')"
new Promise((resolve, reject) => {
(function(i,s,o,g,r,a,m){
a=s.createElement(o),m=s.getElementsByTagName(o)[0];
a.innerText=g;
a.onload=r;m.parentNode.insertBefore(a,m)}
)(window,document,'script',script, resolve())
}).then(() => console.log('Sure did!'))
It doesn't need to be wrapped in a Promise, but doing so allows you to resolve the promise when the script loads, helping prevent race conditions for long-running scripts.
Append script to body:
$(document).ready(function() {
$("<script>", { src : "bootstrap.min.js", type : "text/javascript" }).appendTo("body");
});
Another way you can do it if you want to append code is using the document.createElement method but then using .innerHTML instead of .src.
var script = document.createElement( 'script' );
script.type = 'text/javascript';
script.innerHTML = 'alert("Hey there... you just appended this script to the body");';
$("body").append( script );
I tried this one and works fine. Just replace the < symbol with that \x3C.
// With Variable
var code = "\x3Cscript>SomeCode\x3C/script>";
$("#someElement").append(code);
or
//Without Variable
$("#someElement").append("\x3Cscript>SomeCode\x3C/script>");
You can test the code here.
Can try like this
var code = "<script></" + "script>";
$("#someElement").append(code);
The only reason you can't do "<script></script>" is because the string isn't allowed inside javascript because the DOM layer can't parse what's js and what's HTML.
I wrote an npm package that lets you take an HTML string, including script tags and append it to a container while executing the scripts
Example:
import appendHtml from 'appendhtml';
const html = '<p>Hello</p><script src="some_js_file.js"></script>';
const container = document.getElementById('some-div');
await appendHtml(html, container);
// appendHtml returns a Promise, some_js_file.js is now loaded and executed (note the await)
Find it here: https://www.npmjs.com/package/appendhtml
Just create an element by parsing it with jQuery.
<div id="someElement"></div>
<script>
var code = "<script>alert(123);<\/script>";
$("#someElement").append($(code));
</script>
Working example: https://plnkr.co/edit/V2FE28Q2eBrJoJ6PUEBz
I'm trying to develop extension that works only on specified pages - If page owner adds global variable into their code (for eg. ACCEPT_STATS = true;) I want to execute specified code.
I've already bind my function to the onload event, i've also found solution how to do that in Firefox:
var win = window.top.getBrowser().selectedBrowser.contentWindow;
if (typeof win.wrappedJSObject.ACCEPT_STATS !== 'undefined') {
// code to run if global variable present
}
but I couldn't make this work under Chrome. Is there any possibility to access document's global variable throw Chrome Extension code?
My extension's code is injected as a content-script.
Yes, including script into the page does run in an isolated context from the pages runtime script.
However, it is possible to work around the isolated worlds issue by pushing inline script into the runtime context via a script tag appended to the document's html. That inline script can then throw a custom event.
The included script in the isolated context can listen for that event and respond to it accordingly.
So code in your included script would look something like this:
// inject code into "the other side" to talk back to this side;
var scr = document.createElement('script');
//appending text to a function to convert it's src to string only works in Chrome
scr.textContent = '(' + function () {
var check = [do your custom code here];
var event = document.createEvent("CustomEvent");
event.initCustomEvent("MyCustomEvent", true, true, {"passback":check});
window.dispatchEvent(event); } + ')();'
//cram that sucker in
(document.head || document.documentElement).appendChild(scr);
//and then hide the evidence as much as possible.
scr.parentNode.removeChild(scr);
//now listen for the message
window.addEventListener("MyCustomEvent", function (e) {
var check = e.detail.passback;
// [do what you need to here].
});
The javascript running on the page is running in a different "isolated world" than the javascript that you inject using content scripts. Google Chrome keeps these two worlds separate for security reasons and therefore you can't just read window.XYZ on any window. More info on how isolated worlds work : http://www.youtube.com/watch?v=laLudeUmXHM
The correct way of implementing this is by communicating with the page is via window.postMessage API. Here're how I would go about it :
Inject a content script into each tab
Send a message to the tab via window.postMessage
If the page understands this message, it responds correctly (again via window.postMessage)
Content script executes the code that it needed to execute.
HTH
From what I have read JQuery's getScript function loads the script file in a global context using a function called 'global eval'. Is there a particular setting or method to change this so it will instead load within the function I am calling it from?
If I do the following code name returns undefined as its not loading the script in the local context.
function callscript(){
var name='fred';
getScript(abc.js);
}
//abc.js:
alert(name);
I believe I have found the solution using a regular JQuery ajax call. The trick is you set the datatype to 'text' as otherwise if its script or if use getScript or the alternative .get() it will auto run the script inside and place it in the global context.
function abc(){
var msg="ciao";
$.ajax({
url: 'themes/_default/system/message.js',
success: function(data){
eval(data);
},
dataType: "text"
});
}
//message.js
(function() {
alert(msg);
})();
This alerts 'ciao' as expected :)
Before anyone says anything yes I'm using eval but its perfectly fine in this situation.
As you already noticed, there's nothing in the docs regarding this. I double checked the source code and found that the underlying call has no options for you to pass to override this behavior.
// http://code.jquery.com/jquery-1.9.1.js
...
getScript: function( url, callback ) {
return jQuery.get( url, undefined, callback, "script" );
},
...
As far as I can tell, loading a script asynchronously into a local scope is not possible with jQuery. jQuery's API doesn't give you any other means to configure its usage like this.
I am still investigating how it might be possible using some other technique.
Ok i know this is 2017, 4 years later, but it seems jQuery team never bothered to address this issue, well sort of. I had the same problem and i think this is the solution, the actual intended way of using getScript in a local context. What I noticed was that there is no way that code could be easily eval'd in a local context against your code, which jQuery has no idea how it is going. I haven't gone deeper, but if you look at the jQuery source, how it is injecting the script into the document, it's genius, it avoids eval altogether. The script it therefore ran as if it's a file that was imported through script tag. Without further ado...
I have decided to do the vice-versa of the situation, it better explains what's going on. You can then reverse it to that example in question.
If you noticed getScript actually sends a unique ID to the server in the query string. I don't know why they didn't mention this in documentation. Use that to identify returned scripts. But you have to do something in the backend...
let imports;
$.getScript("scripts.php?file=abc.js", (data, textStatus, jqXHR) => {
window[jqXHR.getResponseHeader('X-scriptID')](imports);
alert (imports.name);
});
abc.js:
imports.name = 'fred';
backend wraps whatever script we are getting scripts.php:
// code that gets the file from file system into var $output
$output = file_get_contents($_REQUEST['file']);
// generate a unique script function name, sort of a namespace
$scriptID = "__script" . $_REQUEST['_'];
// wrap the script in a function a pass the imports variable
// (remember it was defined in js before this request) we will attach
// things we want to become local on to this object in script file
$output = "window.".$scriptID."=function(imports) { ".$output." };";
// set the script id so we can find this script in js
header ("X-scriptID: " . $scriptID);
// return the output
echo $output;
What going is that the js requests a script through getScript, but it doesn't request directly to the file it uses a php script to fetch the contents of the file. I am doing this so that i can modify the returned data and attach headers that are used to id the returned script (this is large app in mind here where a lot of scripts are requested this way).
When getScript runs the returned script in the browser as usual, the actual content of the script are not ran, just a declaration of the wrapper function with a unique name __script1237863498 or something like (the number was given by getScript upon requisition of that script earlier), attached to the global window object.
Then js uses that response to run the wrapper function and inject properties into the imports object... which become local to the requesting whatever's scope.
I don't know jQuery implementation, but the reason name is returning undefined is because name is a private property of the callscript object. To negate this, you could declare the variable outside of the function call:
var name = ''; //Declare name outside of the function
function callscript(){
name='fred';
getScript('abc.js'); //Shouldn't it be $.getScript? and argument should be passed as a string
}
//abc.js:
console.log(name) //Returns undefined
callscript(); //Call the script
console.log(name); //Returns "fred"
// global.js
var global1 = "I'm a global!";
// other js-file
function testGlobal () {
alert(global1);
}
In a Firefox extension I am currently developing using the addon builder, I open a page in a new tab and I would like to call a JS function defined in a script on this page. For this I use this code:
var toOpenTab = require("tabs");
toOpenTab.on('open', function(tab){
toOpenTab.on('ready', function(tab){
tab.attach({
contentScript:
"function showFile(){PageSpecificFunction()};window.onload=showFile();"
});
});
});
I implement the window.onload event to be sure that the script containing the PageSpecificFunction() definition is loaded in the page, even though I don't think it is necessary (because I use the toOpenTab.onReady event).
The problem is: PageSpecificFunction() is not defined. I know the function is correctly defined and works fine because I can call it in the firebug console and it works perfectly.
Is there a way to make my extension call this function once my page is opened ?
You need to use the global unsafeWindow object:
unsafeWindow.PageSpecificFunction();
However this is a security risk
I know that for safety reasons that this is not easy to achieve, however there would be a way to do so as firebug does...
Please help, would like to invoke some script in the page's context to achieve some effect...
Basically, I would like to achieve two functionality:
1. add jQuery to any web page automatically if not already exist.
2. when open certain address, call a method of that page to auto notify the server. (an ajax functionality of the page)
I have tried to inject on the body, no luck.
tried to get the window object, which however do not have access to call the function.
Will try to change the location to something like: javascript:alert('test inject');
Many thx.
OK, after reading some official documentation and the GreaseMonkey's source, I get the following method which basically works for me.
Hope it will save sb's hour:
var appcontent = document.getElementById("appcontent"); // browser
if (appcontent) {
appcontent.addEventListener("DOMContentLoaded", function (evnt) {
var doc = evnt.originalTarget;
var win = doc.defaultView;
var unsafeWin = win.wrappedJSObject;
// vote.up is the function on the page's context
// which is take from this site as example
unsafeWin.vote.up(...);
}, true);
}
}
Greasemonkey does that. If you are developing your own extension with similar functionality, you can use Components.utils.evalInSandbox.