How to inject jquery to any webpage [duplicate] - javascript

This question already has answers here:
How do I include a JavaScript file in another JavaScript file?
(70 answers)
Closed 8 years ago.
Is there any way to inject jQuery into any page as we do with javascript(from url).
with javascript we do this
javascript:alert("b");
I tried this but I don't know why it dosen't work
javascript:var x = document.getElementsByTagName("head")[0];
var y = document.createElement("script");
y.src = "http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js";
x.appendChild(y);
var a = document.getElementsByTagName("body")[0];
var b = document.createElement("script");
b.innerHTML = "$('p').css('border','3px solid red')"
a.appendChild(b);

This is a bookmarklet code to inject jquery in any webpage:
javascript: (function (){
function l(u, i) {
var d = document;
if (!d.getElementById(i)) {
var s = d.createElement('script');
s.src = u;
s.id = i;
d.body.appendChild(s);
}
} l('//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js', 'jquery')
})();
Update:
I removed the http: part from the URL per #Monkpit comment, which is very important and saves a lot of problems.

Since you are loading jQuery asynchronously, the jQuery variable is not available immediately. This means you cannot use jQuery on the next line; you need to wait until the browser loads jQuery and executes it.
The solution is to use one of the following techniques:
use delay (assume that the script loads after x seconds)
use polling (check typeof jQuery === "function" every x milliseconds)
use callback parameter (append query string such as ?callback=scriptloaded, requires server- side support)
use script element's onload event as described below
function injectScriptAndUse() {
var head = document.getElementsByTagName("head")[0];
var script = document.createElement("script");
script.src = "//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js";
script.onload = function() {
$("p").css("border", "3px solid red");
};
head.appendChild(script);
}
<p>Paragraph</p>
<button onclick="injectScriptAndUse();">Click to load jQuery and change style of the paragraph</button>

You forgot a semicolon in row 8. This is the code without errors:
javascript:var x = document.getElementsByTagName("head")[0];
var y = document.createElement("script");
y.src = "http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js";
x.appendChild(y);
var a = document.getElementsByTagName("body")[0];
var b = document.createElement("script");
b.innerHTML = "$('p').css('border','3px solid red')";
a.appendChild(b);
You can inject jQuery in Chrome by putting it as a bookmark. Just copy the code above, create a new bookmark of a random website. Right click on the bookmark and choose 'Edit', paste the code in the URL box and choose 'Save'. When you click on the bookmark the jQuery script will be injected.
-Lucas

Related

Why I have problem with $(document).ready?

I'm learning jQuery but I have a problem.
Here the code:
var script = document.createElement('script');
script.src = 'https://code.jquery.com/jquery-3.4.1.min.js';
script.type = "text/javascript";
var pt = document.createElement('script');
pt.src = 'https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js';
document.getElementsByTagName('head')[0].appendChild(script);
document.getElementsByTagName('head')[0].appendChild(pt);
$(document).ready(function() {
alert("ti vedo");
$.post('wait.php', function(data) {
alert("ti vedo2");
var dati = JSON.parse(data);
alert(data);
for (var i = 0; i <= dati.length; i++) {
var node = $(document.createElement("span"));
var content = $(document.createElement("div"));
var code = dati[i];
var text = $(document.createTextNode(code));
node.append(text);
content.append(node);
$("#boxMessage").append(content);
}
});
});
I use alert to check the error, but I can't see the first alert. So the problem is $(document)... but I don't understand why. I'm making a mistake when I include the jQuery library? Thank you for the Help!
You're getting the error because you're trying to access jQuery (via $) before it's available.
You can run your jQuery-related code after the script was really loaded:
var script = document.createElement('script');
script.src = 'https://code.jquery.com/jquery-3.4.1.min.js';
script.type="text/javascript";
document.getElementsByTagName('head')[0].appendChild(script);
script.addEventListener('load', function(){
alert("ti vedo");
$.post('wait.php',function(data){
alert("ti vedo2");
var dati=JSON.parse(data);
alert(data);
for(var i=0; i<=dati.length; i++){
var node=$(document.createElement("span"));
var content=$(document.createElement("div"));
var code=dati[i];
var text=$(document.createTextNode(code));
node.append(text);
content.append(node);
$("#boxMessage").append(content);
}
});
});
Also, you don't need two different versions of jQuery simultaneously.
The order of activities is:
A script element to load jQuery 3.4.1 is added to the DOM
A script element to load jQuery 3.5.1 is added to the DOM
The $ function is called, but $ is undefined, so the script terminates with an exception
jQuery 3.4.1 is loaded, adding $ to the environment
jQuery 3.5.1 is loaded, overwriting $
Use a regular <script> element to load your dependencies instead of trying to load them half way through executing your script.

How do I load a new script after the page is done loading?

I have two separate script files (script1.js, script2.js). Each of the files has its own functions/variables defined in it. For the sake of simplicity, I will assume each file holds a separate variable. So the files will look like:
script1.js
var x = 2;
script2.js
var y = 2;
I am using the scripts in index.html:
index.html
<button onclick="change()">Change script</button>
<script id="file" src="script1.js"></script>
<script>
function change() {
var file = document.getElementById("file");
if(file.src.slice(-10) == "script1.js") {
file.src = "script2.js";
} else {
file.src = "script1.js";
}
}
</script>
But when I change the src attribute for the script, the loaded script does not change. So even after switching scripts, x has the value 2 while y is undefined.
How do I switch the script after the page has finished loading?
Not sure what you want to accomplish, but as far as loading of javascript is concern, you can use:
$("#id_of_button").click(function(){
$.getScript('helloworld.js', function() {
//do whatever you want to accomplish here....
});
});
More detail here
A better way may be to keep the related code in separate functions in same js file and calling the specific function to override the logic based upon your condition check. Though I'm still not clear what you are trying to achieve. Could I get some scenario based idea to get it clear?
You have to create a new script in order to loaded it, the problem is that you also want to maintain the position of the script.
So here I wrote an example that will replace the old script and insert the new one at the same position.
Read the comment to understand how this work.
function change() {
var file = document.getElementById("file"); // get the script you want to change
var newscript = document.createElement("script"); // create new script
newscript.src = "https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js" // set the new script src
newscript.setAttribute("id","file"); // set the id to the same id as the old script
newscript.type = 'text/javascript';
file.parentNode.insertBefore(newscript, file); // insert the new script before the old one
file.remove() // remove the old script
var callback= function(){ // when the script has been loded then test and see if jQuery is working now
$("body").append("<p>Jq loaded</p>"); // no error then jQuery has been loaded
}
newscript.onreadystatechange = callback;
newscript.onload = callback;
}
<script id="file" src="script1.js"></script>
<button onclick="change()">Change script</button>
You can try this: https://codepen.io/anon/pen/mvMZOR
HTML
<button type="button">Change script</button>
<script id="file" src="script1.js"></script>
Javascript
var index = 1;
var scriptId = 'file';
var button = document.querySelector('button');
button.addEventListener('click', function() {
// Remove the old script
document.getElementById(scriptId).remove();
// Create the new one
var s = document.createElement('script');
// Add the id you want, in this case "file"
s.id = scriptId;
// It will return "script1.js" or "script2.js" alternatively
s.src = 'script' + (index++ % 2 + 1) + '.js';
// Append your new script at the end of your body
document.querySelector('body').append(s);
});

Loading Inline Javascript through an AJAX load through jQuery

I have a similar problem to this question.
Loading Javascript through an AJAX load through jQuery?
I want to load an HTML page into a div container using Ajax and JQuery's .load() . The html page has javascript on it that loads a weather widget from http://www.showmyweather.com/
This is the script:
<script type="text/javascript" src="http://www.showmyweather.com/weather_widget.php? int=0&type=js&country=ca&state=Ontario&city=Hamilton&smallicon=1&current=1&forecast=1&background_color=ffffff&color=000000&width=175&padding=10&border_width=1&border_color=000000&font_size=11&font_family=Verdana&showicons=1&measure=C&d=2013-11-11"></script>
I don't know how to include the widget in the DOM other than placing the script inline the html page. If there is a way to use this script and add it in using $.getscript(); that would be nice, but I can't figure it out.
var element = document.createElement("iframe");
document.body.appendChild(element);
var frame = window.frames[windows.frames.length - 1];
frame.document.write('<scr' + 'ipt type="text/javascript" src="http://www.showmyweather.com/weather_widget.php?int=0&type=js&country=ca&state=Ontario&city=Hamilton&smallicon=1&current=1&forecast=1&background_color=ffffff&color=000000&width=175&padding=10&border_width=1&border_color=000000&font_size=11&font_family=Verdana&showicons=1&measure=C&d=2013-11-11"></sc'+ 'ript>');
This is the way it's done with mootools in Asset.javascript:
var loadScript = function (source, properties) {
properties || (properties = {});
var script = document.createElement('script');
script.async = true;
script.src = source;
script.type = 'text/javascript';
var doc = properties.document || document, load = properties.onload || properties.onLoad;
return delete properties.onload, delete properties.onLoad, delete properties.document,
load && (script.addEventListener ? script.addEventListener("load", load) : script.attachEvent("readystatechange", function() {
[ "loaded", "complete" ].indexOf(this.readyState) >= 0 && load.call(this);
}))
doc.getElementsByClassName("head")[0].appendChild(script);
}
Now you can call loadScript("script url", {document: window.frames[0].document}) and it will load the script in the window. Just need to pass it an external document in options and a script.

Check if Javascript script exists on page

I have a bookmarklet that I've made and it loads a script from my server onto the users current page. However I have an if check in my script that if a condition is not met then no action is taken. However if the user then meets that condition then the code is run, but has caused there to be two sets of scripts inserted into their page. Can i prevent this?
<a href="javascript: (function () {
var jsCode = document.createElement('script');
jsCode.setAttribute('src', 'http://xxx.co.uk/xxx/script.js');
document.body.appendChild(jsCode);
}());">Bookmarklet</a>
You can check whether your script is loaded like this:
function isMyScriptLoaded(url) {
if (!url) url = "http://xxx.co.uk/xxx/script.js";
var scripts = document.getElementsByTagName('script');
for (var i = scripts.length; i--;) {
if (scripts[i].src == url) return true;
}
return false;
}
Alternatively, you could do something like this:
<a href="javascript:
if (!jsCode) {
var jsCode = document.createElement('script');
jsCode.setAttribute('src', 'http://xxx.co.uk/xxx/script.js');
document.body.appendChild(jsCode);
}
">Bookmarklet</a>
This "pollutes" the global namespace with the jsCode variable, but that might be a necessary evil. You could rename it to something that is unlikely to appear in the document where the bookmarklet is run.
Please note that while the javascript URI scheme is okay for bookmarklets as in this case, it's not considered to be a good practice for normal use.
Just check the selector length. Here's an example using jQuery:
if ($('script[src="http://xxx.co.uk/xxx/script.js"]').length > 0) {
//script exists
}
You can place id attributes on your script tags and use document.getElementById('your-id') to identify whether the script is on the page before adding.
if (!document.getElementById('your-id')) {
// append your script to the document here, ensure it has its id attribute set to 'your-id'
}
Solution with ES6, no jQuery:
const url = 'http://xxx.co.uk/xxx/script.js';
function scriptExists(url) {
return document.querySelectorAll(`script[src="${url}"]`).length > 0;
}
if(scriptExists(url)) {
...
}
It's not recommended to inline JS into HTML. Instead add event listeners:
function bookmark() {
if(scriptExists(url)) {
...
}
}
const button = document.querySelectorAll('a.bookmark');
button.addEventListener('click', bookmark, false);
In case working with local and live alternatively.
The exact URL may change. I think the ID method is better.
This is a combination of Two StackOverflow answers.
if (!document.getElementById('your-id')) {
addScript("your_script_src"); //adding script dynamically
addCSSFile("your_css_src"); // adding css files
}
function addScript(path) {
var head = document.getElementsByTagName("head")[0];
var s = document.createElement("script");
s.type = "text/javascript";
s.src = path;
s.id = "your-id";
head.appendChild(s);
}
function addCSSFile(path) {
var head = document.getElementsByTagName("head")[0];
var s = document.createElement("style");
s.type = "text/css";
s.src = path;
head.appendChild(s);
}
if you create a variable in the global scope (window.yourVariable) and check if that exists already then you can decide if you want to add your jsCode snippet code or run whatever you are running in script.js
if (document.getElementById('element-id')) {
// if exist must do something
}
hi, this is worked for me, please try it if you still need it

innerHTML to insert script in body (for ZeroClipboard) not working

I'm building <div> elements using AJAX, and I want to add ZeroClipboard functionality. Firebug shows the code is building correctly, and when I copy it into a raw HTML test page it works too. The builds are not happening at onload, but down the track.
The code is as follows, calling some functions that create the new elements:
dom_append_child_with_onclick ("img",export_id,"icon_active",report_heading_id, "event.cancelBubble = true;");
dom_append_child ("div",export_script_id,"",report_heading_id);
text = "<script language='JavaScript'>var clip" +rnum +"=new ZeroClipboard.Client();clip"+rnum+".setText('');clip"+rnum+".addEventListener('mouseDown',function(client){alert('firing');clip"+rnum+".setText(document.getElementById('SL40').value);});clip"+rnum+".glue('XR"+rnum+"','RH"+rnum+"');</script>";
document.getElementById(export_script_id).innerHTML=text;
My question: when you insert a script into the <body>, do you have to do something to get it to fire? The script appears not to be doing its thing, and I can't get the alert 'firing' to display.
Note: the cancelBubble is to stop the onClick function of the underlying element. It may be unnecessary if I can get the flash working.
Thanks.
You can just inject your script into the page as a DOM object, but this does not work in all browsers:
var s = document.createElement("script");
s.type = "text/javascript";
s.innerText = "var clip" +rnum +"=new ZeroClipboard.Client();clip"+rnum+".setText('');clip"+rnum+".addEventListener('mouseDown',function(client){alert('firing');clip"+rnum+".setText(document.getElementById('SL40').value);});clip"+rnum+".glue('XR"+rnum+"','RH"+rnum+"');";
document.getElementsByTagName("head")[0].appendChild(s);
Or, for better compatibility, you probably want to just declare a function which sets this up in your page, and then just call the function with the rnum as the parameter.
e.g.
function useZeroClipboard(rnum) {
window["clip" + rnum] = new ZeroClipboard.Client();
cwindow["clip" + rnum].setText('');
window["clip" + rnum].addEventListener('mouseDown', function(client){
alert('firing');
window["clip" + rnum].setText(document.getElementById('SL40').value);
});
window["clip" + rnum].glue('XR"+rnum+"','RH"+rnum+"');
}
Then you can just call that in your code:
useZeroClipboard(rnum);
Instead of writing the script block.
Here is a method that recursively replaces all scripts with executable ones:
function replaceScriptsRecurse(node) {
if ( nodeScriptIs(node) ) {
var script = document.createElement("script");
script.text = node.innerHTML;
node.parentNode.replaceChild(script, node);
}
else {
var i = 0;
var children = node.childNodes;
while ( i < children.length) {
replaceScriptsRecurse( children[i] );
i++;
}
}
return node;
}
function nodeScriptIs(node) {
return node.getAttribute && node.getAttribute("type") == "text/javascript";
}

Categories