In Javascript, is it possible to pass a variable into <script> "src" parameter? - external

Is it possible in Javascript to pass a variable through the src parameter? ie.
<script type="text/javascript" src="http://domain.com/twitter.js?handle=aplusk" />`
I'd like twitter.js to look and see if a "handle" was passed before doing what I need it to do and returning its response back to the originating page calling twitter.js.
I had originally created a function in twitter.js that did the following:
function getHandle() {
var vars = [], hash, username;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++) {
hash = hashes[i].split('=');
if (hash[0] == 'handle')
username = hash[1];
}
return username;
}
The problem, and it makes sense, is that window.location.href is not going to work on a file that I'm calling from <script src="" />
Thanks!

I can see two solutions here.
First: you can process those GET parameters on the server where the twitter.js is hosted, so that it will dynamically change the js file. For example, you file is:
var handle = {{ handle }};
And your server somehow processes the file, replacing that twitter.js template file dependent on what request was sent.
The second option would be to set the global variables on the page where twitter.js is loaded, like this:
<script type="text/javascript">
window.twitter_js_handle = 'aplusk';
</script>
<script type="text/javascript" src="http://domain.com/twitter.js" />
And in twitter.js:
var handle = window.twitter_js_handle || null;

I use the following pattern to convert query variables from <script src="script.js?foo=bar&baz=zing"></script> to an object containing key:value pairs. Code is placed at the top of script.js:
var getVars = {};
(function(){
var scripts, currentScript, queryString;
scripts = document.getElementsByTagName('script');
currentScript = scripts[ scripts.length - 1 ];
queryString = currentScript.getAttribute('src').split("?").pop().split('&');
for(var i=0;i<queryString.length;i++){
var keyVal = queryString[i].split('=');
getVars[ keyVal[0] ] = keyVal[1];
}
}());
// console.info( getVars );
// Object { foo="bar", baz="zing"}
This probably won't work with deferred / asynchronously added script elements, as it relies on immediate code execution.

Sure. But the only way you can access that parameter though is through server-side. So, make twitter.js a PHP page (using mod_rewrite or whatever) that grabs $_GET['handle'] and then serves itself as Content-Type: text/javascript and just dump the contents of the js.

I suggest to use more safe approach - must add an ID:
<script id="myTargetScript" src="http://example.com/file.js?param=value" />
then in your .js file
function GetParams(target_id)
{
var getVars = {};
if( document.getElementById(target_id) )
{
var queryString = document.getElementById(target_id).getAttribute('src').split("?").pop().split("&");
for(var i=0;i<queryString.length;i++){
var keyVal = queryString[i].split('=');
getVars[ keyVal[0] ] = keyVal[1];
}
}
return getVars;
}
// console.log( GetParams('myTargetScript') );

Related

HTML <form> input blocked after WASM loads

Please could somebody help me to resolve this problem?
I have canvas, inserted in html and drawn usng WebAssembly in C, however it seems to block the HTML form input fields - I cannot type anything once the wasm module is loaded and runs...
I use emscripten_set_main_loop_arg() in C instead, of requestAnimationFrame() in JS:
const int simulate_infinite_loop = 1; // call the function repeatedly
const int fps = -1; // call the function as fast as the browser wants to render (typically 60fps)
emscripten_set_main_loop_arg(render, &cbp, fps, simulate_infinite_loop);
Later, I insert it in HTML:
<script type='text/javascript'>
var Module = {};
fetch('app/aghdr.wasm')
.then(response =>
response.arrayBuffer()
).then(buffer => {
Module.canvas = document.getElementById("canvas");
Module.wasmBinary = buffer;
var script = document.createElement('script');
script.src = "app/aghdr.js";
script.onload = function() {
console.log("Emscripten boilerplate loaded.")
}
document.body.appendChild(script);
});
</script>
Does anybody know, hot to ensure that normal HTML form processes messages while WASM module is running?
See: http://inters.cloud/test3/
Perhaps it's caused by emscripten_set_keypress_callback().
When a argument callback returns non-zero, event.preventDefault() blocks a keypress event.

Passing a specific url query param from main url into the iframe url

This is what I have.
URL = abc.com/?em=xyz&fn=123
I have an iframe on the page which I want to share some of the param data as follows...
iframe= def.com/xyz
As you can see I just want one of the url params from the main source url to carry across to the iframe, to be part of the url, not an added param on the iframe string. It would always be the single param 'em' that would be carried across, all other params would be ignored.
I think this was clear, but just to show an example of correct iframe = def.com/xyz and wrong would be an iframe with the url = def.com/?em=xyz. I know the latter seems possible in Javascript. I just cannot work out the former. Thanks
Hope someone has any help.
The site is currently on Wordpress if that makes a difference. The iframe url is an external link,not wordpress
Thanks
Right, I have a solution that is working for me so thought I would share. It is important to note that this will probably only work if you are using Wordpress...
Step 1. I created a new page template , called page-iframe php. which references a content file called content-iframe php
In this file I created the iframe code..
<iframe src="domain.com/<?php echo do_shortcode('[urlparam param="em" /]') ?></iframe>
This uses the URL Params Wordpress plugin to read the url and place the param of choice into the iframe which is hard coded into the page template, rather than added in the content/edit area of the wordpress back end.
The only drawback to this as I see it will mean a new page template for every domain you want to use inside the iframe. I only require one domain to be referenced so this is a solution for me.
Purely javascript:
First a function to grab the parameters in the parent URL:
function getQueryVariable(variable)
{
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if(pair[0] == variable){return pair[1];}
}
return(false);
}
Next, call the function to get the 'em' parameter value and store as a variable. Also check that it is defined and not erroneous.
var myParam = getQueryVariable("em");
if ((typeof myParam !== "undefined") && (myParam !== false)) {
Next, create your iframe URL:
var iframeURL = "def.com/".concat(myParam);
Next, assign the iframe URL in your html to this new iframeURL:
document.getElementById('iFrameName').src = iframeURL;
}
Optional; sending the url without an em parameter. You could have done this already in your html.
else{
document.getElementById('iFrameName').src = "http://def.com/";
}
All together:
function getQueryVariable(variable)
{
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if(pair[0] == variable){return pair[1];}
}
return(false);
}
var myParam = getQueryVariable("em");
if ((typeof myParam !== "undefined") && (myParam !== false)) {
var iframeURL = "def.com/".concat(myParam);
document.getElementById('iFrameName').src = iframeURL;
}
else{
document.getElementById('iFrameName').src = "http://def.com/";
}

Pass array from server side function using google script and html

I have an html page that will be served to a google sheet app to be used as a UI. I would like to access an array from a server side function within the html file. I am having trouble accessing a returned array. Here is what I have:
in html file:
<div id="id1">
Starting 1
</div>
<div id= "id2">
Starting 2
</div>
<script type="text/javascript">
document.getElementById("id1").innerHTML = "A change";
</script>
<script type="text/javascript">
function onSuccess(numUnread) {
alert('You have ' + numUnread[0]
+ ' unread messages in your Gmail inbox.');
document.getElementById("id2").innerHTML = numUnread[0];
}
google.script.run.withSuccessHandler(onSuccess)
.getPermits();
</script>
In code.gs:
function getPermits()
{
var permits = [];
for(var i = 0; i < 10; i++)
{
permits.push('Element ' + i);
}
return permits;
}
Right now I am just trying to figure out why the div with id = "id2"
does not get changed to the first element from the passed array. Instead, it is not changed. Also, there is no alert. If I change the return of the gePermits() function to a string, both the div and the alert work as I would expect.
Thanks in advance!
Some types are not passed trough HTMLService, but you can always STRINGFY and PARSE it, try:
return JSON.stringify(permits);
and in the html:
function onSuccess(numUnread) {
numUnread = JSON.parse(numUnread);

SAPUI5 get single property from JSON-Model

I am currently trying to figure out how I can retrieve a single value from a sap.ui.model.json.JSONModel
in my main view:
var gConfigModel = new sap.ui.model.json.JSONModel();
var getConfigCallback = function(config) {
gConfigModel.setData(config);
};
oController.getConfiguration(getConfigCallback);
console.log(gConfigModel);
in my controller:
getConfiguration : function(callback) {
var sServiceUrl = "/sap/opu/odata/sap/xxx/ConfigurationSet('Initialize')";
var config = {};
callback(config);
$.getJSON(sServiceUrl).done(function(data) {
config = data.d;
callback(config);
});
},
In my console.log statement I can see that the data was successfully passed from the backend and successfully set to the JSON model. My requirement is to store the value of attribute Editable in a single variable.
I already tried gConfigModel.getProperty('/'), didnt work. tried to access gConfigModel.oData was undefined .. How can I store it in a single value?
Solution Comment: If you catch data from a backend, you have to take care how long it takes. data can be available later then expected, in my case I added 1s timeout, afterwards I can access the property easily
setTimeout(function() {
console.log(gConfigModel.getProperty('/Editable'));
}, 1000);
I wouldn't advise using the model's getData() method since it is deprecated.
A much better solution is to use gConfigModel.getProperty("/Editable")
(I'm using the root slash here since your property resides in the root of your model)
In the same way, you can also set your data:
gConfigModel.setProperty("/Editable", <your new value>) instead
First of all, thanks for the effort to find solutions of our Problems! (at least, those regarding It stuff.. :) )
I've found a solution which I think is a little bit more save because the timeout is maybe somewhat arbitrary - it would depend on the machine or the amount of data that is to be fetched?
Therefore, I am using an attachRequestCompleted function:
with sUrl_2="path-to-my-service";
var oModel_2 = new sap.ui.model.json.JSONModel(sUrl_2);
oModel_2.attachRequestCompleted(function(data) {
//now, i can access the data stored in the oModel_2, either by getProperty, or by DOM: oModel_2.oData.d.Vendor
gv_selLieferant = oModel_2.getProperty("/d/Vendor");
gv_selEinkOrg = oModel_2.getProperty("/d/PurchOrg");
gv_selEinKGru = oModel_2.getProperty("/d/PurGroup");
});
<script src="https://openui5.hana.ondemand.com/resources/sap-ui-core.js" id="sap-ui-bootstrap" data-sap-ui-theme="sap_bluecrystal" data-sap-ui-libs="sap.m"></script>
<script>
function getConfiguration(callback) {
var sServiceUrl = "/sap/opu/odata/sap/xxx/ConfigurationSet('Initialize')";
var config = {};
var data = {
"d": {
"_metadata": "",
"Backup01": "01",
"Editable": "True"
}
};
setTimeout((function() {
config = data;
callback(config);
})(), 2000);
};
var gConfigModel = new sap.ui.model.json.JSONModel();
var getConfigCallback = function(config) {
gConfigModel.setData(config);
alert(gConfigModel.getProperty("/d/Editable"));
};
getConfiguration(getConfigCallback);
</script>

Google Apps Script, HTML addClickHandler ServerHandler does NOT work

Can anyone confirm that HTML widgets accept ClickHandlers on the Server side ? I can't get my below code to work.
I create a serverHandler (and for good measure I have even added a useless callback element). Subsequently, I add it to a HTML.addClickHander (for good measure I have even added it to .addMouseUpHandler as well). The function is NOT executed.
var mouseclick = app.createServerHandler("handleTrainingClick_").addCallbackElement(lstFilter);
var params = [ "fromOrg", "trainingTitle", "dueDate", "medical", "status" ];
var resultSet = blSelectActiveTrainings_();
while (resultSet.hasNext()) {
var training = resultSet.next();
var html = TRAINING_ROW;
for (var pI in params) {
html = html.replace("$"+params[pI], training[params[pI]]);
}
pnlList.add(app.createHTML(html).setId(training.id).addClickHandler(mouseclick).addMouseUpHandler(mouseclick)
.addMouseMoveHandler(mousemove).addMouseOutHandler(mouseout).addMouseOverHandler(mouseover));
}
function handleTrainingClick_(e) {
Logger.log(e.source);
var app = UiApp.getActiveApplication();
return app;
}
HTML widgets server side handlers work just fine. It was an incorrect reference in my code. Thanks all.