I'm writing this code for an extension but It returns:
Origin chrome-extension://gjganecebobheilkbpmhmocibjckgidc is not allowed by Access-Control-Allow-Origin
var randomstring = '';var jsid = 0;
for (var i=0; i<20; i++) {
var rnum = Math.floor(Math.random() * "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz".length);
randomstring += "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz".substring(rnum,rnum+1);
}
function addS(file){
var xmlHttp = null;
xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET", file, false );
xmlHttp.send( null );
jsid = jsid + 1;
var s = document.createElement('script');
s.type = 'text/javascript';
// s.src = file;
s.innerHTML = xmlHttp.responseText;
s.async = "true";
s.id = randomstring+"_unique"+jsid;
s.className = randomstring;
document.head.appendChild(s);
}
addS('https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js');
addS('http://domain.com/functions.js'');
I would use jQuery but I can't because it breaks the source code of the page, what I want is to do the same as this, but in javascript and skipping that error
function addS(file){
jsid = jsid + 1;
$.get(file, function(data) {
var string = '<script type="text/javascript" async="true" id="'+randomstring+"_unique"+jsid+'" class="'+randomstring+'">'+data+'</script>';
$('head').append(string);
});
Additional Info
I'm gonna insert jquery.js and functions.js with an ID like this tags:
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" async="true" id="AWhAXksocT6o6OrBxT28_unique1" class="AWhAXksocT6o6OrBxT28"></script>
<script type="text/javascript" src="http://domain.com/functions.js" async="true" id="AWhAXksocT6o6OrBxT28_unique2" class="AWhAXksocT6o6OrBxT28"></script>
with this code:
function addS(file){
jsid = jsid + 1;
var s = document.createElement('script');
s.type = 'text/javascript';
s.src = file;
s.async = true;
s.id = randomstring+"_unique"+jsid;
s.className = randomstring;
document.head.appendChild(s);
}
I need this ID (via var randomstring) to keep alive, that's the main problem because I will need to delete both after function ends but it returns
functions.js: Uncaught ReferenceError: randomstring is not defined using this code
$(document).ready(function(){
alert("Functions loaded");
//Do some functions....
$("."+randomstring).delete();
});
Thanks!
You can't perform a cross-domain ajax request unless the domain you are requesting from implements CORS.
What you are doing currently IS a cross-domain ajax request. If you instead do as Sirko suggested and request it by making the src of the script element you are appending the url to the ajax request, it will properly make the request.
function addS(file){
//var xmlHttp = null;
//xmlHttp = new XMLHttpRequest();
//xmlHttp.open( "GET", file, false );
//xmlHttp.send( null );
//jsid = jsid + 1;
var s = document.createElement('script');
s.type = 'text/javascript';
s.src = file;
//s.innerHTML = xmlHttp.responseText;
s.async = "true";
s.id = randomstring+"_unique"+jsid;
s.className = randomstring;
document.head.appendChild(s);
}
What is the purpose of this function? In what context is it used? What does it accomplish?
As far as I can see, you're just pasting the content of a file into the script tag.
So why not pass the file url directly to the src parameter of the script tag instead?
function addS( file ) {
var scriptEl = document.createElement( 'script' );
scriptEl.setAttribute( 'src', file ) ;
document.head.appenChild( scriptEl );
}
Related
I need to add a Javascript file from the server to the LocalStorage and site header.
i try this code but some things wrong??
var s = document.createElement("script");
s.type = "text/javascript";
s.src = localStorage.theImage;
s.title = "myJavaScript";
$("head").append(s);
function addScript() {
var csvRequest = new Request({
url: "splitNumber.js",
onSuccess: function (response) {
var responseFile = response;
var file = responseFile;
var reader = new FileReader();
reader.onload = function (e) {
var s = document.createElement("script");
s.type = "text/javascript";
s.src = reader.result;
localStorage.theImage = reader.result;
$("head").append(s);
}
reader.readAsDataURL(file);//attempts to read the file in question.
});
}
}
Thanks.
Hi I have a stylesheet and JavaScript function which loads in all the required files for that template.
However I am having a bit of an issue due to when the other script tags run within the template file (plan js code) it does not wait for the required files to load.
So what you have happening is scripts not recognizing functions and other JS functions.
JS Code
<script type="text/javascript">
var uid = '{$smarty.session.ipet_user}';
function stylesheet(url) {
var s = document.createElement('link');
s.rel = 'stylesheet';
s.async = false;
s.href = url;
var x = document.getElementsByTagName('head')[0];
x.appendChild(s);
}
function script(url) {
var s = document.createElement('script');
s.type = 'text/javascript';
s.async = true;
s.src = url;
var x = document.getElementsByTagName('head')[0];
x.appendChild(s);
}
(function () {
script('https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js');
script('https://apis.google.com/js/api:client.js');
script('https://maps.googleapis.com/maps/api/js?libraries=places&key=AIzaSyBk99v0F4qkmvxifqOD48YktK-QO-3kopI');
script('./templates/main/user-theme/javascript/google.js');
script('plugins/getmdlselect/getmdl-select.min.js');
script('./templates/main/user-theme/javascript/facebook.js');
script('./templates/main/user-theme/javascript/newprofile.js');
script('./templates/main/javascript/zipcode.js');
stylesheet('https://opensource.keycdn.com/fontawesome/4.7.0/font-awesome.min.css');
stylesheet('https://fonts.googleapis.com/css?family=Roboto');
stylesheet('https://fonts.googleapis.com/icon?family=Material+Icons');
stylesheet('./templates/main/user-theme/tpl-files/material.act.css');
stylesheet('plugins/dropzone/dropzone.css');
stylesheet('plugins/stepper/stepper.min.css');
stylesheet('./templates/main/user-theme/tpl-files/style.css');
stylesheet('./templates/main/style/newprofile.css');
stylesheet('plugins/getmdlselect/getmdl-select.min.css');
})();
</script>
You can use load event of <script> and <link> element, Promise constructor and Promise.all() to return a resolved Promise once all requested resources have loaded by passing an array of URL's to request to Array.prototype.map() where each array of URL's is concatenated to a single array where each function is called which returns a Promise
function stylesheet_(url) {
return new Promise(function(resolve, reject) {
var s = document.createElement('link');
s.rel = 'stylesheet';
// s.async = false;
s.href = url;
var x = document.getElementsByTagName('head')[0];
x.appendChild(s);
s.onload = resolve;
s.onerror = reject;
})
}
function script(url) {
return new Promise(function(resolve, reject) {
var s = document.createElement('script');
s.type = 'text/javascript';
s.async = true;
s.src = url;
var x = document.getElementsByTagName('head')[0];
x.appendChild(s);
s.onload = resolve;
s.onerror = reject
})
}
function loadStylesAndScripts(styleList = Array(), scriptList = Array()) {
return Promise.all(
styleList.map(stylesheet_)
.concat(scriptList.map(script))
)
}
let requests = loadStylesAndScripts();
requests.then(function() {
console.log("styles and scripts loaded")
})
.catch(function(err) {
console.log("an error occurred requesting styles and scripts")
})
I'm trying to load a js and a css file from within a javascript in chrome I can see that both files are loaded, the mofo alert is triggered, and then the test alert, but not the test2 alert.
Why is that, is there an error in the javascript I can't see?
function loadScript(url, callback){
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = url;
script.onreadystatechange = callback;
script.onload = callback;
document.getElementsByTagName('script')[0].appendChild(script);
}
function loadCss(url, callback){
var elem = document.createElement('link');
elem.href = url;
elem.type = 'text/css';
elem.rel = 'stylesheet';
elem.media = 'all';
document.getElementsByTagName('script')[0].appendChild(elem);
}
var coptaJQStart = function() {
var jQuery_1_11_3 = $.noConflict(true);
alert('test');
};
var coptaCssStart = function() {
alert('test2');
};
loadScript('https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js', coptaJQStart);
loadCss('http://www.tffan.com/copta.css', coptaCssStart);
alert('mofo');
You have to attach call back function in loadCss
elem.onreadystatechange = callback;
elem.onload = callback;
function loadScript(url, callback){
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = url;
script.onreadystatechange = callback;
script.onload = callback;
document.getElementsByTagName('script')[0].appendChild(script);
}
function loadCss(url, callback){
var elem = document.createElement('link');
elem.href = url;
elem.type = 'text/css';
elem.rel = 'stylesheet';
elem.onreadystatechange = callback;
elem.onload = callback;
elem.media = 'all';
document.getElementsByTagName('script')[0].appendChild(elem);
}
var coptaJQStart = function() {
var jQuery_1_11_3 = $.noConflict(true);
alert('test');
};
var coptaCssStart = function() {
alert('test2');
};
loadScript('https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js', coptaJQStart);
loadCss('http://www.tffan.com/copta.css', coptaCssStart);
alert('mofo');
I have a service of job portal which other users can use for their sites and blogs. they copy embed code from my site, paste it in their site and display job board in their webpage. how create this embed code anyone can help me.
Here is example monster.com publisher website.
click Get sample code button.
<div id="MonsterJobSearchResultPlaceHolderIy8AAA_e_e" class="xmns_distroph"></div>
<script type="text/javascript">
(function() {
var oScript = document.createElement('script');
oScript.type = 'text/javascript';
oScript.async = true;
oScript.src = ('https:' == document.location.protocol ? 'https://' : 'http://') + 'publisher.monster.com/Services/WidgetHandler.ashx?WidgetID=EAAQgDMlA5vzabXFzuv86ZpLpA--&Verb=Initialize';
var oParent = document.getElementsByTagName('script')[0];
oParent.parentNode.insertBefore(oScript, oParent);
})();
</script>
<a id="monsterBrowseLinkIy8AAA_e_e" class="monsterBrowseLink fnt4" href="http://jobsearch.monster.com/browse/">View More Job Search Results</a>
there are many ways to reach your goal. As you didn't explain your need explicitly, I just provide a simple example:
<script type='text/javascript' charset='utf-8'>
var iframe = document.createElement('iframe');
document.body.appendChild(iframe);
iframe.src = 'URL OF CONTENT YOU WANT TO PROVIDE';
iframe.width = 'THE WIDTH YOU WANT';
iframe.height = 'THE HEIGHT YOU WANT';
</script>
modify the code according to your need
escape this code in your html
have fun with your awesome embedded widget!
How To Create Embed With Javascript in .cs
Note: localhost:3197/website/js/embed/form.js'; // give your js path
FormBuilder(921,'MjEzNjkxMjU='); in this method first parameter give your form height and second your form name or Id. there Id is encoded format
StringBuilder sb = new StringBuilder();
sb.Append("<script type='text/javascript'>");
sb.Append("(function(d, t) { var s = d.createElement(t), options = {");
sb.Append("'async':true };");
sb.Append("s.src = ('https:' == d.location.protocol ? 'https://' : 'http://') + 'localhost:3197/website/js/embed/form.js';");
sb.Append("s.onload = s.onreadystatechange = function() {");
sb.Append("var rs = this.readyState; if (rs) if (rs != 'complete') if (rs != 'loaded') return;");
sb.Append("try { frm = new FormBuilder("+Form Height+",'"+FormId+"');frm.initialize(options);frm.display(); }");
sb.Append("catch (e) {}};");
sb.Append("var scr = d.getElementsByTagName(t)[0], par = scr.parentNode; par.insertBefore(s, scr);");
sb.Append("})(document, 'script');</script>");
txtjavascript.Value = sb.ToString(); // text box name
After Create embed script Simple and Easy Way Paste this script where you want to show in other page after that
(function(d, t) { var s =
d.createElement(t), options = {'async':true }; s.src = ('https:' ==
d.location.protocol ? 'https://' : 'http://') +
'localhost:3197/website/js/embed/form.js'; s.onload =
s.onreadystatechange = function() {var rs = this.readyState; if (rs)
if (rs != 'complete') if (rs != 'loaded') return; try { frm = new
FormBuilder(921,'MjEzNjkxMjU='); frm.initialize(options);
frm.display(); }catch (e) {}}; var scr =
d.getElementsByTagName(t)[0], par = scr.parentNode;
par.insertBefore(s, scr);})(document, 'script');
After That in your js file Create fuction like this and create iFrame ans create querystring where you fetch the form from database.
function FormBuilder(fHeight, formid) {
var iframe = document.createElement('iframe');
iframe.style = "height:" + fHeight + "px; width:100%; border:none";
iframe.setAttribute('allowTransparency', true);
iframe.frameBorder = "0";
iframe.scrolling = "no";
iframe.src = "http://localhost:3197/form/show-form?id="+ formid;
document.body.appendChild(iframe);
}
I am doing like this but not working:-
I am trying to insert the pixel in iframe and then append it to the body.
jQuery('#subscribr').append('<iframe>
<script language="javascript" src="http://www.abc/static/st.v2.js"></script>
<script language="javascript">
var ef_event_type="transaction";
var ef_transaction_properties = "ev_ProductViews=1";
/*
* Do not modify below this line
*/
var ef_segment = "";
var ef_search_segment = "";
var ef_userid="xxxx";
var ef_pixel_host="pixel.abc.net";
var ef_fb_is_app = 0;
effp();
</script>
</iframe>');
enter code here
Scripts like that appear to break when </script> is included in the string. A workaround to that could be to add the elements through dom manipulation:
iframe = $('<iframe>');
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "http://www.abc/static/st.v2.js"; // Or:
script.text = "Your code here!"
iframe[0].appendChild(script);
iframe.appendTo('#subscribr'))
This is the solution which worked for me..
var s = document.createElement("script");
s.type = "text/javascript";
s.src = "http://www.abc/static/st.v2.js";
// Use selector here
jQuery("#subscribr").append(s);
Working sample: http://fiddle.jshell.net/f2x7G/
var doc = null;
if(iframe.contentDocument) doc = iframe.contentDocument;
else if(iframe.contentWindow) doc = iframe.contentWindow.document;
else if(iframe.document) doc = iframe.document;
if(doc == null) throw "Document not initialized";
doc.open();
var script = doc.createElement("script");
script.type = "text/javascript";
// script.src = 'http://www.abc/static/st.v2.js';
script.text = "alert('voila!');"
doc.appendChild(script);
doc.close();