Internally referenced javascript is not loading when content is loaded via ajax - javascript

I am updating a div content via ajax call. The response(html) which i get contains a reference to an internal JavaScript file.
The referenced javascript is not getting loaded. How can I solved the issue.
Below is how I am setting it to a div.
document.getElementById('content-wrapper').innerHTML = data;
The file is loaded correctly when i set the content using jQuery's .html() function. But for that we have to disable 'unsafe-eval' in our content security policy. So jQuery is not an option.
#mplungjan answers did help but i am getting below eror

Try this
const wrapper = document.getElementById('content-wrapper')
wrapper.innerHTML = data;
const scr = wrapper.querySelector("script");
const newScr = document.createElement("script");
newScr.src = scr.src;
try {
document.head.appendChild(newScr)
} catch (e) {
console.log("nope")
}
const data = `This is a script <script src="https://worldwide.espacenet.com/scripts/powered_by_espacenet.js"><\/script> embedded in a string`
const wrapper = document.getElementById('content-wrapper')
wrapper.innerHTML = data;
const scr = wrapper.querySelector("script");
const newScr = document.createElement("script");
newScr.src = scr.src;
console.log(newScr.src);
// this is to handle the document.write in this particular script
const myWrite = document.write;
document.write = function(str) {
wrapper.innerHTML += str
}
try {
document.head.appendChild(newScr)
} catch (e) {
console.log("nope")
}
<form name=""></form>
<div id="content-wrapper"></div>

Related

JavaScript XMLHttpRequest return status 0

I'm pretty new to JavaScript / TypeScript and I was writing this tiny piece of TS code to retreive the HTML from another page on my server and put it on a <div id='container'> tag.
let container = document.getElementById("container") as HTMLDivElement;
let req = new XMLHttpRequest();
function getContent(page: string): string {
let content = "";
const basePath = "content/";
const url = basePath + page;
req.open("GET", url);
req.send();
content = req.responseText;
container.innerHTML = content;
console.log(req.status);
return content;
}
getContent('home');
Now, when I open the page on the browser (I'm using GitHub Pages for hosting) all I get is a blank page and a req.status of 0 in the console.
Of course the file content/home.html exists. I tried both getContent('home') and getContent(home.html) but neither worked.
What am I doing wrong?
Thank you to all.

Dynamic iframe content from js response

I have a page where I'm dynamically creating an empty iframe. Then I need to populate the iframe content by retrieving some js-script response data. Everything works fine when I call js URL:
(function(d) {
var iframe = d.body.appendChild(d.createElement('iframe')),
doc = iframe.contentWindow.document,
options = {
objid: 152,
key: 316541321
},
src = "host/widget.js",
uri = encodeURIComponent(JSON.stringify(options));
iframe.id = "iframewidget";
iframe.width = 200;
iframe.height = 300;
var html = '<body onload="var d=document;' +
'd.getElementsByTagName(\'head\')[0].appendChild(d.createElement(\'script\')).src=\'' + src + '\'">';
doc.open().write(html);
doc.close();
})(document);
But I need to run the widget.js with some dynamic parameter. Is there a way to pass the uri variable value to the script? I use pure JavaScript not jQuery
Here's a quick modification of your code to show how its possible.
Your doc variable is the document element of the iFrame. Setting a variable on it will allow you to access it from code running within the iFrame.
https://jsfiddle.net/78gf5e8q/
(function(d) {
var iframe = d.body.appendChild(d.createElement('iframe')),
doc = iframe.contentWindow.document,
options = {
objid: 152,
key: 316541321
},
//src = "host/widget.js",
uri = encodeURIComponent(JSON.stringify(options));
doc.someVar = "Hello World!";
iframe.id = "iframewidget";
iframe.width = 200;
iframe.height = 300;
var html = '<body onload="var d=document;' +
'd.getElementsByTagName(\'head\')[0].appendChild(d.createElement(\'script\')).innerHTML=\'alert(document.someVar)\'">';
doc.open().write(html);
doc.close();
})(document);
Edit: you were also passing in a non existent var called js into doc.open().write(js); I changed it to .write(html);
Edit 2: For cross domain you'll probably get "Permission Denied" on that var.

Dynamically Replace a URL with JS and Greasemonkey

Im tying to replace a Java script include using Greasemonkey, but I'm afraid it will break quickly because it is not dynamic. Here and example of my situation.
This is the include statement from the original site:
<script src="/asset/js/app.js?dc12383"></script>
The ending ?dc12383 is what I assume to be some type of version number.
I currently replace the js using the code:
function createScript(js, id) {
var s = document.createElement('script');
if (id) s.id = id;
s.type = 'text/javascript';
try { s.innerHTML = js; }
catch(e) { s.innerText = js; }
return s;
}
function replaceJs() {
var js = {
"asset/js/app.js?dc12383": ' *STUFF TO REPLACE*'
};
for (var i in js) {
document.body.appendChild(createScript(js[i], i));
}
}`
Any ideas on how to ignore that ending ?..... in the include?

Dynamic script tag using server active notification

When using server and client in same machine by ajax connectivity it shows the inactive state of server. On using dynamic script tag it doesn't reflect the inactivness of server. How could this be resolved?
we have included these functions in a .js file.
function JSONscriptRequest(fullUrl) {
this.fullUrl = fullUrl;
this.noCacheIE = '&noCacheIE=' + (new Date()).getTime();
this.headLoc = document.getElementsByTagName("head").item(0);
this.scriptId = 'JscriptId' + JSONscriptRequest.scriptCounter++;
}
JSONscriptRequest.scriptCounter = 1;
JSONscriptRequest.prototype.buildScriptTag = function () {
this.scriptObj = document.createElement("script");
this.scriptObj.setAttribute("type", "text/javascript");
this.scriptObj.setAttribute("charset", "utf-8");
this.scriptObj.setAttribute("src", this.fullUrl + this.noCacheIE);
this.scriptObj.setAttribute("id", this.scriptId);
}
JSONscriptRequest.prototype.removeScriptTag = function () {
this.headLoc.removeChild(this.scriptObj);
}
JSONscriptRequest.prototype.addScriptTag = function () {
this.headLoc.appendChild(this.scriptObj);
}
and used the following code in jsp page
// The web service call
var req = <<<url of the service which resides in different server>>>&callback=<callback function>;
// Create a new request object
bObj = new JSONscriptRequest(req);
// Build the dynamic script tag
bObj.buildScriptTag();
// Add the script tag to the page
bObj.addScriptTag();

My Firefox extension to inject CSS wont work

I am busy developing a firefox extension. I am using the Add-on Builder
What it will do:
Get an ID from a PHP page (XMLHttpRequest)
Call another function and send that ID with it
That function inserts CSS with a link tag created by javascript
My Problem:
It won't work. If I alert the currenttheme variable, nothing happens. So the XMLHttpRequest doesn't seem to work.
My code:
main.js:
var Widget = require("widget").Widget;
var tabs = require('tabs');
exports.main = function() {
var pageMod = require("page-mod");
var data = require("self").data;
scriptFiles = data.url("s.js");
pageMod.PageMod({
include: "*.facebook.com",
contentScriptWhen: 'ready',
contentScriptFile: scriptFiles
});
s.js
function addCSS(theTheme) {
var s = document.createElement('link');
s.type = 'text/css';
s.rel = 'stylesheet';
s.href = theTheme+'.css';
(document.head||document.documentElement).appendChild(s);
}
function getData() {
client = new XMLHttpRequest();
try{
client.open('GET','http://localhost:8888/istyla/login/popuplogin/myaccount.php');
} catch (e){
alert( "error while opening " + e.message );
}
client.onreadystatechange = function(){
if (client.readyState ==4){
user_data = client.responseText;
window.user_data = user_data;
var currenttheme = user_data;
window.currenttheme = currenttheme;
addCSS(currenttheme);
}
}
client.send(null);
}
getData();
P.S. The CSS file is in the data folder.
Im very new to this so not sure if I can help. Have you had a look in the error console(ctrl+shift+j) if its complaining about anything? You can console.log() and it will show in here.
Maybe use the Request lib instead of XMLHttpRequest
Here is a snippet from my code:
var Request = require("request").Request;
getUserDetails : function(userID, callback)
{
Request({
url: Proxy.remoteUrl,
content : {command:'getUser',UserID:userID},
onComplete: function(response) {callback(response.json)}
}).get();
}
Content scripts run with the privileges of the page that they are in. So if the page isn't allowed to load http://localhost/, your content script won't be able to do it either. You don't get an immediate error due to CORS but the request will fail nevertheless. What you need to do is to send a message to main.js so that it does the request (extension code is allowed to request any URI) and sends the data back to the content script.
As said, the content script has the same privileged of the web page where is attached, that is meaning you're under the Same Origin Policy.
You can solve the issue as suggested, so sent a message to the add-on code (that is not restricted by the SOP) and post the result back to the content script.
Here an example how the code could be: https://groups.google.com/d/topic/mozilla-labs-jetpack/VwkZxd_mA7c/discussion

Categories

Resources