Dynamically Replace a URL with JS and Greasemonkey - javascript

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?

Related

Gatsby embed forms with script tag in react-helmet

I am trying to embed some forms using react helmet.
My code looks like this:
<Helmet>
<script type="text/javascript">
{var FORMID;
(function(d, t) {
var s = d.createElement(t), options = { 'userName':'USERNAME', 'formHash':'FORMID', 'autoResize':true, 'height':'751', 'async':true, 'host':'wufoo.com', 'header':'show', 'ssl':true };
s.src = ('https:' == d.location.protocol ?'https://':'http://') + 'secure.wufoo.com/scripts/embed/form.js';
s.onload = s.onreadystatechange = function() {
var rs = this.readyState;
if (rs) if (rs != 'complete') if (rs != 'loaded') return;
try {
FORMID = new WufooForm();
FORMID.initialize(options);
FORMID.display();
} catch (e) { }
};
var scr = d.getElementsByTagName(t)[0], par = scr.parentNode;
par.insertBefore(s, scr);
})(document, 'script');}
</script>
</Helmet>
The script is a copy and paste from wufoo form builder. (I replaced the username and form id with the all caps FORMID and USERNAME).
I keep running into errors. Right now this will produce a graphql error (there is not graphql in the page)
There was a problem parsing "/../my-page"; any GraphQL
fragments or queries in this file were not processed.
This may indicate a syntax error in the code, or it may be a file type
that Gatsby does not know how to parse.
and a Module build failed error.
In VS code I get some warnings on the var's saying expression expected. And some other spots where it expects a { or a }. I'm pretty certain the brackets all match up. Again, it's copy and paste from wufoo and this works in plain html/js.
Wrap your script with backticks (`):
<Helmet>
<script type="text/javascript">
{`var FORMID;
(function(d, t) {
var s = d.createElement(t), options = { 'userName':'USERNAME', 'formHash':'FORMID', 'autoResize':true, 'height':'751', 'async':true, 'host':'wufoo.com', 'header':'show', 'ssl':true };
s.src = ('https:' == d.location.protocol ?'https://':'http://') + 'secure.wufoo.com/scripts/embed/form.js';
s.onload = s.onreadystatechange = function() {
var rs = this.readyState;
if (rs) if (rs != 'complete') if (rs != 'loaded') return;
try {
FORMID = new WufooForm();
FORMID.initialize(options);
FORMID.display();
} catch (e) { }
};
var scr = d.getElementsByTagName(t)[0], par = scr.parentNode;
par.insertBefore(s, scr);
})(document, 'script');`}
</script>
</Helmet>

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

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>

Different UI script to execute depending on URL

I have my UI's split up in 2 javascript files. If the URL is of certain patter lets say /test1 then I want script1 to execute or in other words, I want script1 to be added as <include> so the UI renders according to script1 else I want script2 to be added for /test2.
There is no button that triggers these URLs. Its when the page loads -detect URL and load script accordingly.
How can I achieve this?
you can dynamically insert javascript file.
<script type="application/javascript">
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);
}
if(type === "test1")
loadJS('file1.js')
else
loadJS('file2.js');
</script>
using jquery and javascript:
$(document).ready(function(){
var url=location.href//get the page url
var scriptUrl
if(url.indexOf('something')>0){//check for specific string in url
scriptUrl='/script1.js'
}
else{
scriptUrl='/script2.js'
}
var script = document.createElement( 'script' );//create script element
script.type = 'text/javascript';
script.src = scriptUrl;
$("head").append( script );//append newly created script element to head
})
Query String Examples:
?page=test1
?page=test2
Following code will check the value of page and then load the appropriate Script:
$(document).ready(function () {
var page = $.getUrlVar("page");
var scriptToRun = null;
switch (page) {
case "test1":
scriptToRun = "script1.js";
break;
case "test2":
scriptToRun = "script2.js";
break;
}
// Create Script Tag
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = scriptToRun;
$("head").append(script);
});
Be sure to add the following Extension before your $(document).ready code:
$.extend({
getUrlVars: function(){
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++) {
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
},
getUrlVar: function(name){
return $.getUrlVars()[name];
}
});
(This jQuery Extension is not my Code).

Getting twitter shares count, response giving weird output

//this function is the callback, it needs to be a global variable
window.readResponse = function (response){
document.getElementsByTagName('SPAN')[0].innerHTML = response;
}
(function(){
//note the "readResponse" at the end
$URL = "http://www.google.com/"
var src = 'http://cdn.api.twitter.com/1/urls/count.json?url=' + $URL + '&callback=readResponse',
script = document.createElement('SCRIPT');
script.src = src;
document.body.appendChild(script);
})();
That above is my codes to get the shares count. But when I do the request, the response I am getting is
function (){ //note the "readResponse" at the end $URL = "http://www.google.com/" var src = 'http://cdn.api.twitter.com/1/urls/count.json?url=' + $URL + '&callback=readResponse', script = document.createElement('SCRIPT'); script.src = src; document.body.appendChild(script); }
Where as I am expecting the response.count is the actual share count.
I setup a demo here http://jsfiddle.net/zs1dgs45/5/
Any help would be appreciated
Twitter have stopped supporting the share count API. Sorry.

Context When Loading JS File Dynamically [duplicate]

I am a JavaScript newbie and learn by working on a pure JavaScript "project" that calculates mathematical functions. It all works well. Now, as a further step, I want to make the messaging multilingual. The code should be capable of loading the appropriate language file at runtime. For the dynamic loading issue, I read and found solutions on Web pages like this one.
Before writing the dynamic code, I loaded it statically and the test code worked well. The code I am asking for help about is just making the minor difference of loading a "script" element.
The code where I run into problems is the this.getString function, where it is not possible to access the de element in the language file. At line console.log(eval(language, tag));, I get the error message "Uncaught ReferenceError: de is not defined".
//File: Utils/Lang/js/FileUtils.js
function Language(language) {
var __construct = function(dynamicLoad) {
if (typeof language == 'undefined') {
language = "en";
}
// Load the proper language file:
loadFile("js/resources/lang.de.js");
return;
} ()
this.getString = function(tag, strDefault) {
console.log("getString(" + tag + ", " + strDefault + "): ");
console.log("getString(...): document = " + document);
console.log("getString(...): eval(" + language + ", " + tag + ") = ");
console.log(eval(language, tag));
var strReturn = eval('eval(language).' + tag);
if (typeof strReturn != 'undefined') {
return strReturn;
} else {
return (typeof strDefault != 'undefined')
? strDefault
: eval('en.' + tag);
}
}
}
The static test code that works is not included, where I can access the de element.
My question: How to load the language file properly so that the de tag is accessible?
Thank you for your help!
//File: Utils/Files/js/FileUtils.js
function loadFile(filepathname) {
var reference = document.createElement('script');
reference.setAttribute("type", "text/javascript");
reference.setAttribute("src", filepathname);
if (typeof reference != 'undefined') {
document.getElementsByTagName("head")[0].appendChild(reference);
}
console.log("loadFile(\"" + filepathname + "\"): document = " + document);
}
//File: Utils/Lang/js/resources/lang.de.js:
de = {
pleaseWait: "Bitte warten..."
};
//File: Utils/Lang/js/resources/lang.en.js
en = {
pleaseWait: "Please wait..."
};
//File: Utils/Lang/js/TestLanguage.js:
function output() {
console.log("output()");
var codes = ['de', 'en'];
for (var i = 0; i < codes.length; i++) {
var translator = new Language(codes[i]);
var message = "output(): in " + translator.getLanguage() + ": ";
message += translator.getString('pleaseWait');
console.log(message);
}
}
<!--File: Utils/Lang/TestLang.html:-->
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Test languages</title>
<script type="text/javascript" src="../Files/js/FileUtils.js"></script>
<script type="text/javascript" src="js/Language.js"></script>
<script type="text/javascript" src="js/TestLanguage.js"></script>
</head>
<body>
<button name="outputButton" onclick="output();">Click</button>
<br>Please press [F12] so that you can see the test results.
</body>
</html>
When you add the script tag to your document, it is not loaded synchronously. You need to wait for the file to be loaded before you can use the code that was in it.
you may be able to redesign your code to use a script.onload callback:
var reference = document.createElement('script');
// ...
reference.onload = function() {
alert("Script loaded and ready");
};
but for this scenario, if you don't have many language string you may be best to just load them all statically.
How to dynamically load a script file (the most basic version, also there are multiple options to this):
function loadScriptFile(scriptPath, jsFile, callBack)
{
var scriptTag = document.createElement("script"); //creates a HTML script element
scriptTag.language = "JavaScript"; //sets the language attribute
scriptTag.type = "text/javascript";
scriptTag.src = scriptPath + jsFile + ".js"; //the source
if (callBack)
{
scriptTag.onload = callback; //when loaded execute call back
}
var scriptTagParent = document.getElementsByTagName("script")[0];
if (scriptTagParent)
{
scriptTagParent.parentNode.insertBefore(scriptTag, scriptTagParent);
}
else
{
document.body.appendChild(scriptTag);
}
}
How it works:
Run loadScriptFile("scripts", "math", startProgram). The first two arguments will point to your file and folder. The last argument is a callback function. When defined this will be executed once the script tag has finished loading and the script is available in the global scope. The script will be dynamically added to your page. If there is a script element present on the page, this will be added before that (to keep the mark up nice). If not it will be appended to the body. (this is only visual).
The callback part is the most interesting. Since your script will now be asynchronical, you'll need to use callback to tell your program that the necessary files are loaded. This callback is fired when the script file is loaded, so you won't get script errors.
Just a basic example of what I meant in my comment:
This is not an answer to your question, it's an alternative way (I think it's better to manage). Pure Javascript (with help of XML)
XML-file: language.xml
Basic XML structure:
<language>
<l1033 name="english" tag="en-US">
<id1000>
<![CDATA[
Hello World!
]]>
</id1000>
</l1033>
<l1031 name="german" tag="de-DE">
<id1000>
<![CDATA[
Hallo Welt!
]]>
</id1000>
</l1031>
</language>
What did I do:
I constructed a root element called language. Within that wrote two language strings called l1033 for English and l1031 for German. Note that a letter is prepended before the language code. XML will throw an error when a tag starts with a digit. a CDATA block is used to prevent any problems with special characters.
Now the loading will be done by AJAX:
var xmlLoader = new XMLHttpRequest();
xmlLoader.onreadystatechange = trackRequest; //event to track the request, with call back
xmlLoader.open("get", "language.xml", true); //set asynchronous to true
xmlLoader.send(null);
function trackRequest()
{
if (this.status == 200 && this.readyState == 4) //all is good
{
globalLanguageFile = this.responseXML;
startProgram(); //fictive function that starts your program
}
}
Now the XML is loaded. How to load strings from it?
function loadLanguageString(code, id, fallback)
{
var word = fallback;
if (globalLanguageFile.getElementsByTagName("l"+code).length > 0)
{
if (globalLanguageFile.getElementsByTagName("l"+code).[0].getElementsByTagName("id"+id).length > 0)
{
//found the correct language tag and id tag. Now retrieve the content with textContent.
word = globalLanguageFile.getElementsByTagName("l"+code).[0].getElementsByTagName("id"+id)[0].textContent;
}
}
return word; //when failed return fall back string
}
How to call the function:
loadLanguageString(1031, 1000, "Hello World!");
I found the right answer to my question using the info from GarethOwen. Here are the code modifications I had to do:
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Test languages</title>
<script type="text/javascript" src="../Arrays/js/ArrayUtils.js"></script>
<script type="text/javascript" src="../Files/js/FileUtils.js"></script>
<script type="text/javascript" src="../Logic/js/LogicalUtils.js"></script>
<script type="text/javascript" src="js/LanguageUtils.js"></script>
<script type="text/javascript" src="js/TestLanguageUtils.js"></script>
</head>
<!-- body onload="load(null, '../Maths/js/resources')" -->
<body onload="load();">
<button onclick="output();">Click</button><br>
Please press [F12] so that you can see the test results.
</body>
</html>
TestLanguage.html: Augmented the body tag
<body onload="load()">
TestLanguage.js:
2a. Added the load() function requested by the HTML page now:
var gCodes = ['de', 'en', 'tr'];
function load() {
console.log("load()");
for (var i = 0; i < codes.length; i++) {
new Language(codes[i]);
}
}
2b. Using the global gCodes variable also in the output() function
Language.js: To test the whole better, I made the code in the function Language a little bit more elaborate by changing the line in the constructor in function Language(language) to:
// Load the proper language file:
if (eval("gLoaded.indexOf('" + language + "') < 0")) {
loadFile("js/resources/lang." + language + ".js");
gLoaded[gLoaded.length] = language;
}
Thank you for your support! :-)
//Lang/js/Lang.js:
"use strict";
/**
* Object for multilingual message handling.
*
* #param language
*/
function Language(language) {
var __construct = function(dynamicLoad) {
if (typeof language == 'undefined') {
language = "en";
}
// Load the proper language file:
switch (language) {
case "de":
loadFile("js/resources/lang.de.js");
break;
case "tr":
loadFile("js/resources/lang.tr.js");
break;
default:
loadFile("js/resources/lang.en.js");
}
return;
}()
/**
* Returns the language of that object.
*
* #returns The language
*/
this.getLanguage = function() {
var strLanguage;
switch (language) {
case "de":
strLanguage = "German";
break;
case "tr":
strLanguage = "Turkish";
break;
default:
strLanguage = "English";
}
return strLanguage;
}
/**
* Returns the language code of that object.
*
* #returns The language code
*/
this.getString = function(tag, strDefault) {
var strReturn = eval('eval(language).' + tag);
if (typeof strReturn != 'undefined') {
return strReturn;
} else {
return (typeof strDefault != 'undefined') ? strDefault : eval('en.' + tag);
}
}
}
//Lang/js/TestLang.js:
"use strict";
var gCodes = ['de', 'en', 'tr'];
function load() {
console.log("load()");
for (var i = 0; i < gCodes.length; i++) {
new Language(gCodes[i]);
}
}
/**
* Object for multilingual message handling.
*
* #param language
*/
function output() {
console.log("output()");
for (var i = 0; i < gCodes.length; i++) {
var translator = new Language(gCodes[i]);
var message = "output(): in " + translator.getLanguage() + ": ";
message += translator.getString('pleaseWait');
console.log(message);
}
}
//Utils/Files/js/FileUtils.js:
"use strict";
/**
* Object with file utilities
*
* #param filepathname
*/
function loadFile(filepathname) {
var methodName = "loadFile(" + filepathname + "): "
var reference = document.createElement('script');
reference.setAttribute("type", "text/javascript");
reference.setAttribute("src", filepathname);
if (typeof reference != 'undefined') {
document.getElementsByTagName("head")[0].appendChild(reference);
}
reference.onload = function() {
console.log(methodName + "onload(): Language script loaded and ready!");
}
}
Here is the console output:
Here is the output:
load()
loadFile(js/resources/lang.de.js): onload(): Language script loaded and ready!
loadFile(js/resources/lang.en.js): onload(): Language script loaded and ready!
loadFile(js/resources/lang.tr.js): onload(): Language script loaded and ready!
output()
output(): in German: Bitte warten...
output(): in English: Please wait...
output(): in Turkish: Lütfen bekleyiniz...
loadFile(js/resources/lang.de.js): onload(): Language script loaded and ready!
loadFile(js/resources/lang.en.js): onload(): Language script loaded and ready!
loadFile(js/resources/lang.tr.js): onload(): Language script loaded and ready!

Categories

Resources