I am trying to inject a script on page load in head wherein I have to give the page name inside script.
Below is how I am implementing it in my ts file.
**var head = document.getElementsByTagName('head')[0];
var tag = document.createElement("script");
tag.type = 'text/javascript';
tag.innerHTML = "var DDO = {} DDO.pageData = {'pageName': " + pageUrl + "} ";
head.appendChild(tag);**
The script is getting injected however an error is being thrown in the console tab.
ERROR: VM3741:1 Uncaught SyntaxError: Unexpected identifier at appendChild
Try this
var head = document.getElementsByTagName('head')[0],pageUrl="somevalue";
var tag = document.createElement("script");
tag.type = 'text/javascript';
tag.textContent = "var DDO = {}; DDO.pageData = {'pageName': '" + pageUrl + "'} ";
head.appendChild(tag);
To remove previous script element
var script = head.childNodes[0]; //get previous script element
head.removeChild(script); //removing script
you have not provided single quotes for the value of the key pageName
tag.innerHTML = "var DDO = {}; DDO.pageData = {'pageName': " + pageUrl + "} ";
semicolon missing after defining the variable DDO,
and also from where are you injecting in pageUrl, make sure variable is defined.
try having script in external file and injecting in script tag with refrence to that file in case some error in script defined in inner html
document.head, document.body to attach scripts
Correct Answer:
var head = document.getElementsByTagName('head')[0];
var tag = document.createElement('script');
tag.type = 'text/javascript';
tag.id = 'adobedatalayer';
tag.textContent = 'var DDO = {}; DDO.pageData =' + JSON.stringify(pageinfo);
var script = document.getElementById('adobedatalayer');
if (script != null) {
head.removeChild(script);
}
head.appendChild(tag);
I have a problem when trying to use a widget.
The script is as follows:
<script type="text/javascript">
baseUrl = "https://widgets.cryptocompare.com/";
var scripts = document.getElementsByTagName("script");
var embedder = scripts[ scripts.length - 1 ];
(function (){
var appName = encodeURIComponent(window.location.hostname);
if(appName==""){appName="local";}
var s = document.createElement("script");
s.type = "text/javascript";
s.async = true;
var theUrl = baseUrl+'serve/v3/coin/chart?fsym=TPAY*&tsyms=USD';
s.src = theUrl + ( theUrl.indexOf("?") >= 0 ? "&" : "?") + "app=" + appName;
embedder.parentNode.appendChild(s);
})();
</script>
When I access https://widgets.cryptocompare.com/serve/v3/coin/chart?fsym=TPAY*&tsyms=USD from my browser it displays all the data but when using the widget script it does not seem to like the fsym=TPAY&tsym=USD but because cryptocompare lists some currencies that have the same ticker they add a * to the second currency which uses the same ticker name.
Another example of this is PHORE PHR* as they have PHREAK PHR already listed. Funny enough the currencies I would like to use it TPAY* and PHR*.
In my content script, I am using this approach to be able to access web page's variables:
function exec(fn) {
var script = document.createElement('script');
script.setAttribute("type", "application/javascript");
script.textContent = '(' + fn + ')();';
document.body.appendChild(script); //run the script
document.body.removeChild(script); //clean up
}
exec( function(){
var test = websiteVar
chrome.runtime.sendMessage("extensionID", {test: test}, function(response) {
});
});
Where it says extensionID, if I hardcode it, it works. However, I can't use chrome.runtime.id as it is injected in the page. I think I read they don't work in the same context.
Is there a way to get the extension id programatically?
Example of what wOxxOm said above:
function exec(fn) {
var script = document.createElement('script');
script.setAttribute("type", "application/javascript");
script.textContent = '(' + fn + ')("' + chrome.runtime.id +'")';
document.body.appendChild(script); //run the script
document.body.removeChild(script); //clean up
}
exec( function(extensionID){
var test = websiteVar;
chrome.runtime.sendMessage(extensionID, {test: test}, function(response) {
});
});
Im trying to save the client IP address in a variable after retrieving it in JSON form from api.ipify.org. I can get the IP to show if I alert the result but cannot get it to save in a variable for some reason.
This works:
<script>
function getIP(json) {
alert(json.ip);
}
</script>
<script src="https://api.ipify.org?format=jsonp&callback=getIP"></script>
But this does not work:
<script>
var clientIP = ''
function getIP(json) {
clientIP = json.ip;
return clientIP;
}
alert(clientIP);
</script>
<script src="https://api.ipify.org?format=jsonp&callback=getIP"></script>
I would like to be able to store the data in a variable so that I can attach it to an embed that will add it into its automated webhook POST.
<!-- begin video recorder code --><script type="text/javascript">
var IPADDRESSVARIABLE = 'SOME_IP_ADDRESS'
var size = {width:400,height:330};
var flashvars = {qualityurl: "avq/300p.xml",accountHash:"BUNCHOFRANDOMSTUFF", eid:2, showMenu:"true", mrt:120,sis:0,asv:1,mv:0, payload: IPADDRESSVARIABLE};
(function() {var pipe = document.createElement('script'); pipe.type = 'text/javascript'; pipe.async = true;pipe.src = ('https:' == document.location.protocol ? 'https://' : 'http://') + 's1.addpipe.com/1.3/pipe.js';var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(pipe, s);})();
</script>
<div id="hdfvr-content"> </div>
<!-- end video recorder code -->
If I can get the IP address saved as a global variable then I can pass it into the 'payload' key of the 'flash vars'.
The second code example does not work because the variable is only given a value inside of a callback function, which means the alert,which runs synchronously, runs as soon as the javascript interpreter starts reading and running the code line by line, but the getIP function is only called later on when the jsonp request returns a response. Your first code example was the right way to go.
Your alert won't work because your code is not executing synchronously, getIP doesn't get called until after your alert statement. You need to trigger any functionality that depends on clientIP inside your getIP function. Here is an example:
function getIP(json) {
var event = new CustomEvent('iploaded', { detail: json.ip });
document.dispatchEvent(event);
}
document.addEventListener('iploaded', function(event) {
var IPADDRESSVARIABLE = event.detail;
var size = {width:400,height:330};
var flashvars = {qualityurl: "avq/300p.xml",accountHash:"BUNCHOFRANDOMSTUFF", eid:2, showMenu:"true", mrt:120,sis:0,asv:1,mv:0, payload: IPADDRESSVARIABLE};
(function() {var pipe = document.createElement('script'); pipe.type = 'text/javascript'; pipe.async = true;pipe.src = ('https:' == document.location.protocol ? 'https://' : 'http://') + 's1.addpipe.com/1.3/pipe.js';var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(pipe, s);})();
});
// simulate jsonp callback
getIP({ ip: '127.0.0.1' });
Also, no need to return in getIP
Try this :
function getIP(json) {
return json.ip;
}
var json = { "ip": "111.22.33.44"}
var clientIP = getIP(json);
alert(clientIP);
I found a workaround! I stored the result of the IP function into a hidden div to act as a container. I then declared a variable inside the embed code and set it to the innerHMTL. It may not be the most elegant but it does exactly what I want it to!
//hidden container to store the client IP address
<div id = 'ipContainer' style='display:none'></div>
//function to retrieve the client IP address
<script>
function getIP(json) {
document.getElementById('ipContainer').innerHTML = json.ip;
}
</script>
//shortened version of the URL that returns the IP
<script src='http://www.api.ipify.org'><script>
//embed code for the video recorder
<script>
<!-- begin video recorder code --><script type="text/javascript">
var clientIP = document.getElementById('ipContainer').innerHTML;
var size = {width:400,height:330};
//I passed the clientIP variable into the payload element of the flashvars object
var flashvars = {qualityurl: "avq/300p.xml",accountHash:"RANDOM ACCOUNT HASH", eid:2, showMenu:"true", mrt:120,sis:0,asv:1,mv:0, payload:clientIP}; //Here i passed the clientIP which is nor stored as a variable
(function() {var pipe = document.createElement('script'); pipe.type = 'text/javascript'; pipe.async = true;pipe.src = ('https:' == document.location.protocol ? 'https://' : 'http://') + 's1.addpipe.com/1.3/pipe.js';var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(pipe, s);})();
</script>
<div id="hdfvr-content"> </div>
<!-- end video recorder code -->
As Rob says, you're expecting the code to run synchronously but that isn't the case.
Here's a small edit of your code snippet that will work, basically I've wrapped the alert in a function, I then call that function once the getIP function has finished executing.
<script>
var clientIP = ''
function getIP(json) {
clientIP = json.ip;
alertClientIp();
}
function alertClientIp () {
alert(clientIP);
}
</script>
The code design of the above snippet is a bit nasty, if you only need to use the client IP once, then don't bother storing it as a variable, just pass it to the function which executes you "automated webhook POST" logic.
<script>
function getIP(json) {
clientIP = json.ip;
alertClientIp();
}
//Accept the client_ip as a param
function webhookLogic (client_ip) {
//Execute your logic with the client_ip,
//for simplicity I'll stick to your alert.
alert(client_ip);
}
</script>
With regards to your edit
It looks like you have the two sets of logic placed in two separate script elements, could you not merge them into one?
<script>
function getIP(json) {
clientIP = json.ip;
alertClientIp();
}
//Accept the client_ip as a param
function webhookLogic (client_ip) {
//Execute your logic with the client_ip,
//for simplicity i'll stick to your alert.
//Trigger your video wrapper code, unsure if
//if this method of execution will break your app...
videoWrapper(client_ip);
}
//Your video code from your latest edit
function videoWrapper (client_ip) {
var IPADDRESSVARIABLE = client_ip;
var size = {width:400,height:330};
var flashvars = {qualityurl: "avq/300p.xml",accountHash:"BUNCHOFRANDOMSTUFF", eid:2, showMenu:"true", mrt:120,sis:0,asv:1,mv:0, payload: IPADDRESSVARIABLE};
(function() {var pipe = document.createElement('script'); pipe.type = 'text/javascript'; pipe.async = true;pipe.src = ('https:' == document.location.protocol ? 'https://' : 'http://') + 's1.addpipe.com/1.3/pipe.js';var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(pipe, s);})();
}
</script>
If that chain of execution breaks your app then I think you need to go back to the drawing board with regards to the composition of your question, it's clear what you want to do but your question lacks a bit of meta-data as to how this logic all "fits together".
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).