I am using in my website the embedded version of a jsfiddle like so:
<script async src="//jsfiddle.net/mebibou/va5pu0bd/embed/"></script>
I tried to pass parameters in that url like ?foo=bar but I get an error in the console from the script on that url:
Uncaught TypeError: Cannot read property 'parentNode' of null
at createEmbedFrame (?foor=bar:19)
createEmbedFrame # ?foor=bar:19
setTimeout (async)
(anonymous) # ?foor=bar:43
(anonymous) # ?foor=bar:45
(you can see the code that is executed here: http://jsfiddle.net/mebibou/va5pu0bd/embed/?foo=bar)
I also tried to use the iframe version of the embed but it loads another iFrame within that removes the url parameter I put. Is it at all possible? what I want to do is pass parameters from my website to the jsfiddle code, and thought url params would be the easiest way
The error goes away if you remove the trailing slash from the path component:
<script async src="//jsfiddle.net/mebibou/va5pu0bd/embed/?foo=bar"></script>
^
<script async src="//jsfiddle.net/mebibou/va5pu0bd/embed?foo=bar"></script>
The error happens because the jsfiddle.net server strips such slash when composing the uriOriginal variable:
var uriOriginal = "http://jsfiddle.net/mebibou/va5pu0bd/embed?foo=bar"
That leads to a CSS selector that doesn't match your <script> tag:
var uriOriginal = "http://jsfiddle.net/mebibou/va5pu0bd/embed?foo=bar"
var uriOriginalNoProtocol = uriOriginal.split("//").pop()
var target = document.querySelector("script[src*='" + uriOriginalNoProtocol + "']")
console.log("script[src*='" + uriOriginalNoProtocol + "']", target);
However, if your <script> tags omits the slash then the selector does match.
It's worth nothing though that this hack merely prevents the error and allows the fiddle to load and run. It doesn't transmit the original URL parameters to the final iframe because its path is already hard-coded in the JavaScript code generated by the server:
var uriEmbedded = "http://jsfiddle.net/va5pu0bd/embedded/?username=mebibou")
iframe.src = uriEmbedded
target.parentNode.insertBefore(iframe, target.nextSibling)
To sum up, passing URL parameters is probably an unsupported scenario.
Related
I am working on a plugin to modify a URL and update a page. The goal is to get the parent URL, modify it and then offer up a link that the user can click to go to the new URL.
I am able to get the URL and display it, then modify the URL and display it. However, when I try to create a link using the ID, the link URL is to the index.html for the iframe, not the newURL id that I am referencing. I know I am overlooking something but I have been through a ton of HTML documentation and can't solve it. Any help would be greatly appreciated. Image of bad URL
Thanks,
Scott
<!DOCTYPE html>
<html>
<body>
<p id="currentURL"></p>
<p id="newURL"></p>
Click this link to update sort
<script>
var myAssetsServer = "http://localhost:8080"
var startingURL = parent.document.location.href;
var myCustomSort = "imageSupplierImageID,assetType,filename";
var endingURL = myAssetsServer + "/app/#/search//" + myCustomSort + "/?" + startingURL.split("?")[1];
document.getElementById("currentURL").innerHTML =
"The original URL of this page is:<br>" + startingURL;
document.getElementById("newURL").innerHTML = endingURL;
</script>
</body>
</html>
The two main issues to address were
Update the href value of the link element (from comment not an issue in actual code), and
Percent encode the # character as %23 in the URL to send it and what follows to the server:
Hash marks in a URL that are part of identifying a a resource on the server must be percent encoded.
By contrast, fragment identifiers at the end of an URL, e.g.
htpp://www.example.com/page.html#element-id
are used by browsers to request a page from the server and, after rendering the response, scroll down the page to the element with the same id as the fragment identifier.
The first raw hash mark (not the last occurrence) in a link's 'href` string introduces a fragment identifier.
Neither the fragment identifier nor its preceding '#' character are sent to the server as part of a request: they terminate a URL without forming part of it.
See also
Related What are fragment URLs and why to use them?
The description of unsafe characters in section 2.2 of RFC1738
The character "#" is unsafe and should
always be encoded because it is used in World Wide Web and in other
systems to delimit a URL from a fragment/anchor identifier that might
follow it.
Additional issues may need addressing, depending on how the server application is written - or whether the posted code is final:
the double slash // in the URL looks strange but could be by design.
Comma characters in a URL are meant to be encoded as %2C unless being used as separators in the query component. They may work anyway, due to there being no assigned meaning of commas placed before the beginning of the query component, and server code may or may not impose a requirement for their usage (check with the developer).
When running the snippet on Stack Overflow, a dummy page location had to be set (example.com), which then generated undefined in the query component of the generated href value.
Example code snippet with fixes for 1 and 2:
"use strict";
var myAssetsServer = "http://localhost:8080"
var startingURL = "http://www.example.com"; //parent.document.location.href;
var myCustomSort = "imageSupplierImageID,assetType,filename";
var endingURL = myAssetsServer + "/app/#/search//" + myCustomSort + "/?" + startingURL.split("?")[1];
//Fix 1: escape the '#' in the URL
endingURL = endingURL.replace('#', "%23");
document.getElementById("currentURL").innerHTML =
"The original URL of this page is:<br>" + startingURL;
document.getElementById("newURL").innerHTML = endingURL;
//Fix 2: change the URL in the link
var anchorElement = document.querySelector("a[href=newURL]");
anchorElement.href = endingURL;
//Prevent link action on Stack Overflow:
anchorElement.addEventListener("click", function (event) {
console.log("href= %s", this.href)
event.preventDefault();
});
<p id="currentURL"></p>
<p id="newURL"></p>
Click this link to update sort
<p style="border-left: medium solid #DDD; padding-left: 2rem;">
Link deactivated in code snippet - hover over or click to see href value.
I use this code to download file using jquery.
$('#dwnlod').click(function (ee) {
e.preventDefault();
var currentFile = $('#SlideContainer .actv').css('background-image').replace(/^url|[\(\)]/g, '');
alert(currentFile)
document.location.href = currentFile;
});
However, it always does nothing. the reason for this is when I remove e.preventDefault to read the URL I find it distorted.
it rather than the result from alert >>
"https://localhost:660066/Uploads/5c92f430-4aef-41c8-b201-853597935771.jpg"
it displays in a new browser tab >>
https://localhost:660066/Documents/Index/"https://localhost:660066/Uploads/5c92f430-4aef-41c8-b201-853597935771.jpg"
I don't know if I need extra steps with asp.net core routing !!?
It looks like the issue is that currentFile returns a string that is surrounded by quotes and thus the browser is interpreting it as a relative URL (since the scheme isn't at the beginning of the string). Removing the start and end quotes if they exist should get you the behavior you are looking for.
I'm using the Genius API to retrieve the lyrics for a given song and embed them within an HTML <div> tag. I'm interacting with this API using PHP, via an AJAX GET request.
In the event of a successful AJAX request, I retrieve the following HTML from my PHP:
<div id='rg_embed_link_2351532' class='rg_embed_link' data-song-id='2351532'>
Read <a href='https://genius.com/The-1975-the-sound-lyrics'>“The Sound” by The 1975</a> on Genius
</div>
<script crossorigin src='//genius.com/songs/2351532/embed.js'></script>
The script tag returned by the Genius API will embed the lyrics and lyric information when executed.
I'm attempting to import this HTML into my already existing <div>. In this case, the <script> portion will not be executed. I've tried to use an eval() within the 'success' function of my AJAX to dynamically execute this script, but I'm having no success:
$.ajax({
url: 'lyrics.php',
type: 'GET',
async: true,
success: function(success){
geniusHTML = success;
//Insert geniusHTML including script tag into div
var lyricsDiv = document.getElementById("lyricsDiv");
lyricsDiv.innerHTML = geniusHTML;
//Get the script tag from the html and use eval on it
var innerScript = lyricsDiv.getElementsByTagName('script')
eval(innerScript.outerHTML);
}
});
I've tried to eval the:
.outerHTML -- The console shows this value to be: <script crossorigin="" src="//genius.com/songs/2351532/embed.js"></script>
.innerHTML -- Attribute appears to be empty.
.src -- The console shows this value to be: http://genius.com/songs/2351532/embed.js. Theeval() function errors on this with Uncaught SyntaxError: Unexpected end of input.
I feel I am potentially doing this backward. Should I execute the script from my AJAX return before I add it to the div? (The script generates quite a few embed div tags)
EDIT
With instruction from answerer Sjoerd de Wit, I attempted to create a new script tag from the source tag's src attribute, and add it via document.head.appendChild. This did not work, providing the warning:
Failed to execute 'write' on 'Document': It isn't possible to write
into a document from an asynchronously-loaded external script unless
it is explicitly opened.
You should get the src from the script tag and dynamically create and load it in your html
var script = document.createElement("script");
var innerScript = lyricsDiv.getElementsByTagName('script')
script.src = innerScript.src;
document.head.appendChild(script);
using jQuery's .html() instead of javascript's .innerHTML() will automatically evaluate scripts inside the string
so, try to change this line
//Insert geniusHTML including script tag into div
var lyricsDiv = document.getElementById("lyricsDiv");
lyricsDiv.innerHTML = geniusHTML;
//Get the script tag from the html and use eval on it
var innerScript = lyricsDiv.getElementsByTagName('script')
eval(innerScript.outerHTML);
into
$("#lyricsDiv").html(geniusHTML);
SOLUTION
Answering my own question.
The other answers to this question are perfectly acceptable and work in most situations. However, if the external .js file contains a document.write within it, your browser will give you the following warnings:
Failed to execute 'write' on 'Document': It isn't possible to write into a document from an asynchronously-loaded external script unless it is explicitly opened.
One of the ways to get around this is to use Postscribe. Postscribe will override any instances of document.write within javascript passed to it.
In the context of my code -- which, rest assured, I will refactor to make it more efficient -- I retrieve my script tag from my div by getting the outerHTML of the element, then I pass it into postscribe.
With this use case, postscribe takes two arguments; the div to pass the script to, and the script itself. Of course -- you can pass the script inline or via a variable as I have done in the below example:
var myScript = myDiv.getElementsByTagName('script')[0].outerHTML;
postscribe('#myDiv', myScript);
Please see the postscribe documentation linked above for installation instructions and further functionality.
youtube url is not working in javascript,why?
where is the mistake in my code:
$(document).ready(function(){
api_images = ['http://www.youtube.com/watchv=OyQoHmcunk&rel=0&fs=0&width=640&height=360'];
api_titles = ['Title 1'];
api_descriptions = ['']
$.prettyPhoto.open(api_images,api_titles,api_descriptions);
});
You're missing the ? that actually separates the path from the query-string:
api_images = ['http://www.youtube.com/watch?v=OyQoHmcunk&rel=0&fs=0&width=640&height=360'];
// ^
Without it, you should be receiving a 404 response, which a decent javascript debugger would've told you. You are using a debugger, right?
Also, depending on the DOCTYPE in use and whether this is from an inline or external <script>, HTML-encoding the &s may either be necessary or another source of issue:
api_images = ['http://www.youtube.com/watch?v=OyQoHmcunk&rel=0&fs=0&width=640&height=360'];
// ^ ^ ^ ^
i'm trying to get the url and title of any website with this javascript we wrote. i made the javascript in a .HTM and get it from out my regedit in the menuExt. like file://C:\Users\lala\script.htm
here's the script
<script type="text/javascript" defer>
javascript:{var jolExt={url:"http://example.com/script_container.php?id=¬e=",submit:function(a){var b=jolExt.base64.encode(jolExt.strip(document.getElementsByTagName("title")[0].innerHTML));var d=jolExt.base64.encode(jolExt.strip(location.href));
window.open(jolExt.url+d+"¬e="+b,"","width=380,height=335")},submitToOtherJol:function(){jolExt.submit(true)},submitToJol:function(){jolExt.submit(false)},strip:function(a){return a.replace(/ {2,}/g," ").replace(/^ +/g,"").replace(/ +$/g,"")},base64:{_0:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",encode:function(a){var b="";var d,c,h,j,i,f,g;var e=0;a=jolExt.base64._1(a);while(e<a.length){d=a.charCodeAt(e++);c=a.charCodeAt(e++);h=a.charCodeAt(e++);j=d>>2;i=((d&3)<<4)|(c>>4);f=((c&15)<<2)|(h>>6);g=h&63;if(isNaN(c)){f=g=64}else if(isNaN(h)){g=64}b=b+this._0.charAt(j)+this._0.charAt(i)+this._0.charAt(f)+this._0.charAt(g)}return b},decode:function(a){var b="";var d,c,h;var j,i,f,g;var e=0;a=a.replace(/[^A-Za-z0-9\+\/\=]/g,"");while(e<a.length){j=this._0.indexOf(a.charAt(e++));i=this._0.indexOf(a.charAt(e++));f=this._0.indexOf(a.charAt(e++));g=this._0.indexOf(a.charAt(e++));d=(j<<2)|(i>>4);c=((i&15)<<4)|(f>>2);h=((f&3)<<6)|g;b=b+String.fromCharCode(d);if(f!=64){b=b+String.fromCharCode(c)}if(g!=64){b=b+String.fromCharCode(h)}}b=jolExt.base64._2(b);return b},_1:function(a){a=a.replace(/\r\n/g,"\n");var b="";for(var d=0;d<a.length;d++){var c=a.charCodeAt(d);if(c<128){b+=String.fromCharCode(c)}else if((c>127)&&(c<2048)){b+=String.fromCharCode((c>>6)|192);b+=String.fromCharCode((c&63)|128)}else{b+=String.fromCharCode((c>>12)|224);
b+=String.fromCharCode(((c>>6)&63)|128);b+=String.fromCharCode((c&63)|128)}}return b},_2:function(a){var b="";var d=0;var c=c1=c2=0;while(d<a.length){c=a.charCodeAt(d);if(c<128){b+=String.fromCharCode(c);d++}else if((c>191)&&(c<224)){c2=a.charCodeAt(d+1);b+=String.fromCharCode(((c&31)<<6)|(c2&63));d+=2}else{c2=a.charCodeAt(d+1);c3=a.charCodeAt(d+2);b+=String.fromCharCode(((c&15)<<12)|((c2&63)<<6)|(c3&63));d+=3}}return b}}};jolExt.submitToJol();}
when i'm using my add-on i made i only get the path i set on the regedit in the menuExt. Does any1 know's how to solve this. i alraidy tried to putt the full javascript in the string value but it didn't help.
so in short language, i am asking the url but i get the path of my regedit editor in the menuExt. and i need the url of the parent site and the title of the parent site.
Plz help me :)
Regards,
Freezingmoon
The problem is that the document instance in your script is the MenuExt script's document. What you need is the document from which the script was called.
To get this use the external.menuArguments object. This contains the window of the callee. Consider this simple MenuExt script
<script type="text/javascript">
// Get callee's 'window' object
var win = external.menuArguments;
// Get the callee's 'document' object.
var doc = win.document;
// Get the callee's object which invoked this
// (aka: what you right-clicked on)
var src = win.event.srcElement;
// Spit back page title and URL
alert('Viewing ' + doc.title + ' at ' + win.location +
'. You clicked on ' + src + '.');
</script>
To get the item right-clicked on, use external.menuArguments.event.srcElement, as shown above.