Call Chrome.extension.sendRequest from a dynamically inserted js? - javascript

I'm currently trying to insert dynamically a JS block on a webpage using jQuery but it didn't work. I tried this :
var body = $('body');
var injectJs = $('<script type=text/javascript>' +
'$(document).click(function() {' +
'dropMenu("dropMenu1", 0);' +
'});');
body.append(injectJs);
EDIT : 16:26
I've succeed to insert the code by this way :
/* Importation de Tool.js */
var scriptImport = document.createElement('script');
scriptImport.type = 'text/javascript';
scriptImport.src= chrome.extension.getURL('js/Tool.js');
head.appendChild(scriptImport);
/* Injection du script onClick */
var script = document.createElement('script');
script.type = 'text/javascript';
script.innerHTML = "document.addEventListener('click', function(){ dropMenu('slideUp', 0); alert('TRY ME AGAIN'); });";
And dropMenu :
function dropMenu(dropMenuPage, marginLeft)
{
var msg = "";
msg = msg.concat(dropMenuPage, "|", marginLeft);
chrome.extension.sendRequest({dropMenu : msg});
alert('After send');
}
The problem is that the sendRequest is impossible from this page... Someone have an idea ?
Thanks in advance.

You need a closing </script> at the end there...

I think its just your script stag isn't closed
var b= $('body');
var injectJs = $('<script type=text/javascript> $(document).click(function() {alert("yes");});</script>');
b.append(injectJs);

Use eval function, such as eg:
var body = $('body');
var injectJs = eval("$(document).click(function() {alert('hello')})");
body.append(injectJs);

Why not use content scripts for this? Injecting script directly to the page is only required if you need to access js variables from the page. For your dropMenu() a content script should be enough.
You cannot use Chrome API inside injected js. You would need to also inject a content script, and using custom DOM events you would be able to communicate with it from your injected script. Then this content script would be able to call Chrome API and communicate with a background page. Sounds like a pain to me. I would suggest you go this route only if there is no other ways possible.

// Importation of jQuery.js
var scriptImport = document.createElement('script');
scriptImport.type = 'text/javascript';
scriptImport.src= chrome.extension.getURL('js/jquery.js');
head.appendChild(scriptImport);
// Injection of onClick script
var script = document.createElement('script');
script.type = 'text/javascript';
script.innerHTML =
"document.addEventListener('click', function()" +
"{ if(document.getElementById('dropMenu')) {" +
"$('#dropMenu').slideUp(800, function() {" +
"$(this).remove();" +
"});" +
"}});";
I've finally done this, it works :)

Related

Loading a javascript dynamically in angular

I have got the following scenario and problem to solve. Any help will be appreciated.
Scenario
I have an angular application which calls a service(web api) and gets the contents back. The content is added to the html div. The content is as follow:
<script type="text/javascript" src="https://xxxx.com/ws/js/xxxxloader.js" id="theLoader"></script>
<script type="text/javascript">
// The code here look at the if the above script has been loaded properly by //checking the state of above script tag
</script>
I am adding the returned content to the HTML of the component in NgOnInit() as follow.
ngOnInit(){
this.apiService.getContent().subscribe(
d => {
this.responseString = d.toString();
var frag = document.createRange().createContextualFragment(this.responseString);
document.getElementById("theContainer").appendChild(frag);
}
);
}
However, it is failing because the first script tag (#theLoader) has never been loaded properly. I think it is because I am injecting the script tag after Dom has finished loading.
If you can see the better way of injecting the script, can you enlighten me.
Thanks in advance.
You can dynamically inject the JS URL by creating dynamic script tag
ngOnInit(){
function loadScripts(url: string){
var el = document.createElement('script');
el.onload = function(script){
console.log(script + ' loaded!');
// you can call the JS Function
};
el.src = url;
document.getElementsByTagName('body')[0].append(el);
}
</script>
ngAfterViewInit () {
this.loadScript('path to your js');
}
loadScript(url) {
console.log('preparing to load...')
let node = document.createElement('script');
node.src = url;
node.type = 'text/javascript';
document.getElementsByTagName('head')[0].appendChild(node);
}
Try this one :
ngOnInit(){
this.addScripts("https://xxxx.com/ws/js/xxxxloader.js", 'text/javascript');
this.addScripts("https://xxxx.com/js/mail.js", 'text/javascript');
}
addScripts(src, type): void{
var script = document.createElement('script');
script.src = src;
script.type = type;
document.querySelector('body').appendChild(script);
}

Cross browser issue with script tag

I have the below code that will dynamically create the script tag.
<html>
<head>
<title>Applying</title>
</head>
<body>
<script>
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi,
function(m,key,value) {
vars[key] = value;
});
return vars;
}
var variable1 = getUrlVars()["parameter1"];
var myScript = document.createElement('script');
myScript.setAttribute('type', 'text/javascript');
myScript.setAttribute('urlId', '420');
myScript.setAttribute('dataTitle', variable1);
myScript.setAttribute('dataemail', 'admin#domain.net');
document.body.appendChild(myScript);
</script>
<input name="Apply" type="button" id="Apply" value="Apply" ONCLICK="window.location.href='https://www.google.com?'">
</body>
</html>
But somehow the above code doesn't work in IE but it works fine in Chrome. I am not sure what is the reason? Can anybody help me with that?
This whole things doesn't work in IE.
var myScript = document.createElement('script');
myScript.setAttribute('type', 'text/javascript');
myScript.setAttribute('urlId', '420');
myScript.setAttribute('dataTitle', variable1);
myScript.setAttribute('dataemail', 'admin#domain.net');
document.body.appendChild(myScript);
You can dynamically add a script element using the following function.
var create_script = function(data) {
var script = document.createElement('script');
script.type = 'text/javascript';
script.text = data;
//if you have to debug dynamically loaded script in chrome use the following - sourceURL has changed in the recent versions of chrome devetools.
//script.text = data + "\n\n //# sourceURL=" + ns + ".js\n";
//append the script element to body or head or where it seems fit.
document.body.appendChild(script);
}
the "data" parameter is the actual javascript code/URL that will form the part of the script tag. You are missing this in your code.
EDIT:
for non-standard attributes you might want to change the doctype according to http://www.w3schools.com/DTD/dtd_attributes.asp

How do I add dynamic javascript to the head tag from a string, not a file?

I am using Javascript to generate additional custom javascript and then adding it to the HEAD tag. The code below works great adding a javascript file, but what if the script is in a variable just generated?
var scriptTag = document.createElement("script");
scriptTag.setAttribute("type", "text/javascript");
scriptTag.setAttribute("src", "myfile.js");
document.getElementsByTagName("head")[0].appendChild(scriptTag);
Thank you for your attention.
// script text
var txt = "alert('foo');";
var scriptTag = document.createElement("script");
scriptTag.setAttribute("type", "text/javascript");
// append it in a text node
scriptTag.appendChild(document.createTextNode(txt));
document.getElementsByTagName("head")[0].appendChild(scriptTag);
FWIW, you don't need a script tag for this. You can use the Function constructor instead.
var txt = "alert('foo');";
Function(txt)();
var scriptTag = document.createElement("script");
scriptTag.setAttribute("type", "text/javascript");
scriptTag.innerHTML = "What you want here";///....
document.getElementsByTagName("head")[0].appendChild(scriptTag);
Live DEMO
Both answers seem ok specially the one from #gdoron.
I've written a simple example in case you want to do the same thing in jquery: http://jsfiddle.net/bitoiu/EKpGg/
Snippet:
$(function(){
var script = document.createElement( 'script' );
script.type = 'text/javascript';
// script.url = 'some valid url';
$('head').append( script );
});​

javascript - how to insert a script tag to div?

How to do that:
document.getElementById('target').innertHTML = "<script> alert(1); <script>";
<div id="target"></div>
script will be print on browser like a string.How to do is as script ?
I believe it is better to use pure DOM manipulation. Like this :
var s = document.createElement('script');
s.setAttribute('type', 'text/javascript');
s.value = 'alert(1)';
document.getElementById('target').appendChild(s);
Just don't escape your < and >s:
document.getElementById('target').innertHTML = "<script> alert(1); <\/script>";
You cannot use innerHTML for scripts anymore. It won't work and the console will not show any error. Instead you dynamically add scripts.
This is for external scripts:
var newScript = document.createElement("script");
newScript.src = "http://www.example.com/my-script.js";
target.appendChild(newScript);
And this is for inline scripts:
var newScript = document.createElement("script");
var inlineScript = document.createTextNode("alert('Hello World!');");
newScript.appendChild(inlineScript);
target.appendChild(newScript);
Credit to Daniel Crabtree
document.getElementById('target').innertHTML = '<script type="text/javascript"> alert(1); </script>';

Javascript access denied error on page partial load - why?

On thirdpartydomain.com I want to embed a simple <script> tag that pulls in a script from mydomain.com/myscript.js, which simply creates a little <div> and pulls partial page content from mydomain.com/mypage.htm.
Here's the script, adapted from: How to embed Javascript widget that depends on jQuery into an unknown environment
var myEmbedId = '12345';
var myEmbedContainerId = 'myEmbedContainer_' + myEmbedId;
document.write('<div id="' + myEmbedContainerId + '">IF ALL GOES WELL, THIS TEXT WILL BE REPLACED WITH MYPAGE.HTM CONTENTS');
document.write('</div>');
(function (window, document, version, callback) {
var j, d;
var loaded = false;
if (!(j = window.jQuery) || version > j.fn.jquery || callback(j, loaded)) {
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "http://mydomain.com/jquery-1.4.1.min.js";
script.onload = script.onreadystatechange = function () {
if (!loaded && (!(d = this.readyState) || d == "loaded" || d == "complete")) {
callback((j = window.jQuery).noConflict(1), loaded = true);
j(script).remove();
}
};
document.documentElement.childNodes[0].appendChild(script)
}
})(window, document, "1.3", function ($, jquery_loaded) {
$(document).ready(function () {
alert('jquery loaded!');
var myRefreshUrl = 'http://mydomain.com/mypage.htm';
alert('refreshing from ' + myRefreshUrl);
$.get(myRefreshUrl, function(data){
var returnData = data;
alert('return data: ' + data);
$('#' + myEmbedContainerId).html(data); });
alert('load complete v2');
});
});
In IE, I get an Access Denied error from Javascript; in Firefox I just get no data returned.
What's wrong with this?
You cannot create an AJAX request to a different domain from the one that is hosting the current window context.
To pull off what you're describing, you can do something like:
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'http://mydomain.com/dynamic.js?data=somepage.htm';
someContainer.appendChild(script);
Within that dynamic.js, you can wrap the HTML contents in a document.write(). The net effect is the same as inserting the result of the AJAX request at the same point in the DOM.

Categories