I have read all advices how to add external JavaScript file to React application but no one works for me. I'll describe my situation. I have created a tutorial React project and it works fine. Now I want to show a data that I get from server side in some grid , say, jqgrid. I have a JavaScript file that has a function showGrid() to show the grid. So I need to add this file to the project. More precisely I have a React component ShowInGrid and in
render()
method of it I write
let contents = this.state.loading
? <p><em>Loading...</em></p>
: ShowInGrid.renderGrid(this.state.data);
and then
static rendersGrid(data) {
return (
showGrid(data)
);
where showGrid is a function from JavaScript file. To reference to this file I used several ways:
in componentDidMount method I added
var script = document.createElement('script');
script.src = // path of external javascript file.
script.class = "external-script
document.body.appendChild(script);
I get a message
'showGrid' is not defined no-undef
I tried to use
import ScriptTag from 'react-script-tag';
with
< ScriptTag isHydrating={true} type="text/javascript" src="http://my path to js-file">
but I get the same result.
So I really need to know what's wrong and how properly to add JavaScript file to app. A real working example will be really appreciated.
Related
I am using Google App Script and I am relatively new to coding. I am trying to send an email with an HTML body, but the entire formatting is dropped in Gmail.
To fix it, I came across the Juice Inliner Tool to add the CSS stylesheet to the HTML source. But I have no clue how to use it in Google App Script. Please help me with some guidance or any reference code on this.
So far I have the code to convert a Google Doc into an HTML Page. Now I want to input the HTML code finalhtml into the Juice Inline tool and return that code instead of finalhtml.
function doc2html(googleDocId){
const exporturl = 'https://docs.google.com/feeds/download/documents/export/Export?id='+googleDocId+'&exportFormat=html'; //export and hold the document as HTML in the constant exprotUrl
//set the required fetch parameters to run the UrlFetchApp
const fetchParam = {
method :"get",
headers : {
"Authorization":"Bearer "+ScriptApp.getOAuthToken()
},
muteHttpExceptions:true
};
var finalhtml = UrlFetchApp.fetch(exporturl,fetchParam).getContentText(); // holds the actual HTML code for the doc in the variable finalhtml.
GmailApp.sendEmail('mailId','Subject', finalhtml,{htmlBody: finalhtml});
}
I have already mention my js file path in angular.cli, it was loading only one time when angular app was initilizing and when we get back to the component then it was not loading so please give me some suggestion over this.
Thanks for your help in advance.:)
This imay help for you.
Please try to mention it on Index.html. or load script dynamatically on component.
function loadJS(file) {
// DOM: Create the script element
var jsElm = document.createElement("script");
// set the type attribute
jsElm.type = "application/javascript";
// make the script element load file
jsElm.src = file;
// finally insert the element to the body element in order to load the script
document.body.appendChild(jsElm);
}
I am using google app scripts on google sites. I have created a navigation menu, and I embedded it into the page. I want to get the pageURL() from google scripts and retrieve it in my JavaScript page. I tried using the scriptlet to get the value, but it doesn't execute. Here is what I have so far. How can I get access to values in google app scripts and use them in my JavaScript function?
google script (.gs)
function getPageName(){
var site = SitesApp.getSite("site.com", "sitename");
var page = site.getChildren()[0];
var pageName = page.getUrl().split("/").splice(-1)[0];
return pageName;
}
javascript file
var pageName = <?!= getPageName()?>; // doesnt execute, need to get page url
if(pageName == linkName){
// add class here.
}
Since google loads the apps script as an iframe, I tried doing window.location.href, but it doesn't work either. The page name ends up being the name of the google app instead.
An alternative to using scriptlets is to use google.script.run (Client-side API)
It's pretty easy to use. In your case, it should be like this
code.gs
function getPageName(){
var site = SitesApp.getSite("site.com", "sitename");
var page = site.getChildren()[0];
var pageName = page.getUrl().split("/").splice(-1)[0];
return pageName;
}
Javascript File:
function onSuccess(receviedPageName)
{
if(receviedPageName== linkName)
{
// add class here.
}
}//onSuccess
google.script.run.withSuccessHandler(onSuccess).getPageName();
withSuccessHandler(function) is executed if the server-side function returns successfully or withFailureHandler(function) is executed if a server side function fails to complete the task it was assigned.
Give it a try :)
I'd like to inject a couple of local .js files into a webpage. I just mean client side, as in within my browser, I don't need anybody else accessing the page to be able to see it. I just need to take a .js file, and then make it so it's as if that file had been included in the page's html via a <script> tag all along.
It's okay if it takes a second after the page has loaded for the stuff in the local files to be available.
It's okay if I have to be at the computer to do this "by hand" with a console or something.
I've been trying to do this for two days, I've tried Greasemonkey, I've tried manually loading files using a JavaScript console. It amazes me that there isn't (apparently) an established way to do this, it seems like such a simple thing to want to do. I guess simple isn't the same thing as common, though.
If it helps, the reason why I want to do this is to run a chatbot on a JS-based chat client. Some of the bot's code is mixed into the pre-existing chat code -- for that, I have Fiddler intercepting requests to .../chat.js and replacing it with a local file. But I have two .js files which are "independant" of anything on the page itself. There aren't any .js files requested by the page that I can substitute them for, so I can't use Fiddler.
Since your already using a fiddler script, you can do something like this in the OnBeforeResponse(oSession: Session) function
if ( oSession.oResponse.headers.ExistsAndContains("Content-Type", "html") &&
oSession.hostname.Contains("MY.TargetSite.com") ) {
oSession.oResponse.headers.Add("DEBUG1_WE_EDITED_THIS", "HERE");
// Remove any compression or chunking
oSession.utilDecodeResponse();
var oBody = System.Text.Encoding.UTF8.GetString(oSession.responseBodyBytes);
// Find the end of the HEAD script, so you can inject script block there.
var oRegEx = oRegEx = /(<\/head>)/gi
// replace the head-close tag with new-script + head-close
oBody = oBody.replace(oRegEx, "<script type='text/javascript'>console.log('We injected it');</script></head>");
// Set the response body to the changed body string
oSession.utilSetResponseBody(oBody);
}
Working example for www.html5rocks.com :
if ( oSession.oResponse.headers.ExistsAndContains("Content-Type", "html") &&
oSession.hostname.Contains("html5rocks") ) { //goto html5rocks.com
oSession.oResponse.headers.Add("DEBUG1_WE_EDITED_THIS", "HERE");
oSession.utilDecodeResponse();
var oBody = System.Text.Encoding.UTF8.GetString(oSession.responseBodyBytes);
var oRegEx = oRegEx = /(<\/head>)/gi
oBody = oBody.replace(oRegEx, "<script type='text/javascript'>alert('We injected it')</script></head>");
oSession.utilSetResponseBody(oBody);
}
Note, you have to turn streaming off in fiddler : http://www.fiddler2.com/fiddler/help/streaming.asp and I assume you would need to decode HTTPS : http://www.fiddler2.com/fiddler/help/httpsdecryption.asp
I have been using fiddler script less and less, in favor of fiddler .Net Extensions - http://fiddler2.com/fiddler/dev/IFiddlerExtension.asp
If you are using Chrome then check out dotjs.
It will do exactly what you want!
How about just using jquery's jQuery.getScript() method?
http://api.jquery.com/jQuery.getScript/
save the normal html pages to the file system, add the js files manually by hand, and then use fiddler to intercept those calls so you get your version of the html file
is there a method in JavaScript by which I can find out the path/uri of the executing script.
For example:
index.html includes a JavaScript file stuff.js and since stuff.js file depends on ./commons.js, it wants to include it too in the page. Problem is that stuff.js only knows the relative path of ./commons.js from itself and has no clue of full url/path.
index.html includes stuff.js file as <script src="http://example.net/js/stuff.js?key=value" /> and stuff.js file wants to read the value of key. How to?
UPDATE: Is there any standard method to do this? Even in draft status? (Which I can figure out by answers, that answer is "no". Thanks to all for answering).
This should give you the full path to the current script (might not work if loaded on request etc.)
var scripts = document.getElementsByTagName("script");
var thisScript = scripts[scripts.length-1];
var thisScriptsSrc = thisScript.src;
If your script knows that it's called "stuff.js", then it can look at all the script tags in the DOM.
var scripts = document.getElementsByTagName('script');
and then it can look at the "src" attributes for its name. Kind-of a hack, however, and to me it seems like something you should really work out server-side.
script.aculo.us (source) solves a similar problem. here is the relevant code
var js = /scriptaculous\.js(\?.*)?$/;
$$('script[src]').findAll(function(s) {
return s.src.match(js);
}).each(function(s) {
var path = s.src.replace(js, ''),
includes = s.src.match(/\?.*load=([a-z,]*)/);
(includes ? includes[1] : 'builder,effects,dragdrop,controls,slider,sound').split(',').each(
function(include) { Scriptaculous.require(path+include+'.js') });
});
(some parts of this like .each require prototype)