unexpected token error: in bookmarklet - javascript

The idea is to write a simple bookmarklet.
If the question is a possible duplicate kindly point me to it, because i was unsuccessful in finding.
I'm trying to make the current page jquery enabled using the bookmarklet and use certain jquery apis.
Uncaught SyntaxError: Unexpected token ILLEGAL
The above it the error I get using the below sample bookmarklet
javascript:(function(){
var d=document.createElement('script');
d.setAttribute('src', 'http://code.jquery.com/jquery-latest.js');
document.head.appendChild(d);
$('a').each(function(){
alert( $(this).attr('src') );
});
})()
​ If I execute the same code line-by-line in console it works.
Thanks in advance

To make the page wait until jQuery is fully loaded, add a load handler to the script element. This worked in my browser:
javascript:(function(){
var d=document.createElement('script');
d.src = 'http://code.jquery.com/jquery-latest.js';
d.onload = function(){ /* load handler here */
$('a').each(function(){
console.log( $(this).attr('href') );
});
};
document.getElementsByTagName('head')[0].appendChild(d);
})()
I changed your code a little bit (add the src attribute directly as property to the created script element, retrieve the head element in a more classical way, use console.log instead of alert and log the href attribute of all links).

Related

Dynamically executing a <script> tag with an external src attribute using eval

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.

Sharepoint - How to Generate a Scripting Error in Outlook for Test

Hello,
I am trying to test error supression on Sharepoint but I am having some trouble.
This is my process:
On a relatively plain website (all it contains is a colored-in div), I added this script:
<script>
var x[] = 0;
var err = 10/x;
alert(err);
</script>
When setting my Outlook homepage to this site, I see this error:
I also have the following script, which suppresses this message (when adding this to my code, the error message doesn't appear):
<script type="text/javascript">
window.onerror = function(message, url, lineNumber) {
// code to execute on an error
return true; // prevents browser error messages
};
</script>
I want to test this script out on my Sharepoint site, but when I embed the above, error-inducing code onto my Sharepoint homepage and open the page in Outlook, I am not seeing any error messages.
I added the code in the following ways:
1 - Page > Edit > Edit Source > Added the code to the top
2 - Page > Edit > Embed Code > Added the code to various areas of the page
Neither of these methods worked, and the first one actually produced a message telling me that I should use the embed function, which also doesn't seem to work!
I need to generate this error from the Sharepoint page so that I can check **whether the error-suppressing script actually does what it's supposed to. Can **anyone think of what may be going wrong here?
Any help is much appreciated!
This is apparently a known issue in Sharepoint, and can be resolved by using the following function:
SP.SOD.executeFunc('sp.js', 'SP.ClientContext', function(){
//your code goes here...
});
For the purposes of the above test, I was able to generate an error with the following:
<script language='javascript'>
SP.SOD.executeFunc('sp.js', 'SP.ClientContext', function(){
var x[] = 0;
var err = 10/x;
alert(err);
});
</script>
And adding the below suppressed the errors:
<script language='javascript'>
window.onerror = function(message, url, lineNumber) {
return true;
};
</script>
Note that this only worked for me after adding the 2 bits of code in their own, seperate <script> tags. I also had to add language='javascript' to the tags before it would work.
I added the code by embedding some new code, and adding both of the script tags to that web part. Because I was able to produce the error message, I was also able to prove that the error-suppression method worked.

jQuery Error: Uncaught TypeError: $ is not a function

I am having this issue due to using some third party script that is throwing me an error. The script relates to a wordpress plugin that has actually been published by the author.
I am using the 'iLightBox' plugin to display liteboxes for my images. However i need to set which images appear in the lightbox gallery. I have been using the developer website and found the following URL: http://www.ilightbox.net/faq.html
Script 5 appears to do what i need:
jQuery(document).ready(function(){
(function(){
var groupsArr = [];
$('[rel^="ilightbox["]').each(function () {
var group = this.getAttribute("rel");
$.inArray(group, groupsArr) === -1 && groupsArr.push(group);
});
$.each(groupsArr, function (i, groupName) {
$('[rel="' + groupName + '"]').iLightBox({ /* options */ });
});
})();
});
I am running this code in a custom.js file and i can see using 'inspect element' in Chrome that the file is loading correctly but the script is erroring with the following:
"Uncaught TypeError: $ is not a function".
I have read through some posts by other users who explain i need to encapsulate with a function and finish with '(jQuery)' however if i do this it just generates more errors.
Can anyone assist me?
My website where the error is showing: http://www.complete-models.com/uncategorized/16-alien-figure/
If you can change your code just replace $ to jQuery
$('[rel^="ilightbox["]').each(function () {
to
jQuery('[rel^="ilightbox["]').each(function () {
Make sure that you custom.js loaded after jQuery so in html file <scipt> tag for jQuery should be above custom.js

jQuery properties - problem

I use this plugin: jQuery.i18n.properties
I put this code:
/* Do stuff when the DOM is ready */
jQuery(document).ready(loadMessage);
/*
* Add elements behaviours.
*/
function loadMessage() {
jQuery("#customMessage").html("test");
jQuery.i18n.properties({
name:'up_mail_messages',
path:'https://static.unifiedpost.com/apps/myup/customer/upmail/upmail_messages/',
mode:'both',
language:'en',
callback: function() {
var messageKey = 'up.mail.test';
//alert(eval(messageKey));
jQuery('#customMessage').html(jQuery.i18n.prop(messageKey));
}
});
}
I do not understand why, in the customeMessage div it prints out:
[up.mail.test]
instead of the value of it:
up.mail.test=messages loaded from en
Can anybody show me where i am wrong? I;ve spent about two hours on it without finding any clue...
Many Thanks.
Ps: here is the message file: https://static.unifiedpost.com/apps/myup/customer/upmail/upmail_messages/up_mail_messages_en.properties
EDIT: After testing locally, all works good. But if the messages files are located to another host (like in the above example) it seems that it fails...It would be nice if anyone can confirm this...
EDIT 1: It does not work because inside the js script there is an ajax call to read the messages files. Well, as you probably know, Cross-Domain XMLHttpRequest Calls are forbidden in ajax due to the browsers restrictions.
Could I trouble you and test a suspicion of mine?
Replace your first line with:
$(document).ready(function() {loadMessage()});
Also, I note that https://static.unifiedpost.com/apps/myup/customer/upmail/upmail_messages/up_mail_messages.properties returns a 404 error, while the en version works well. Is this intentional?
i don't know what is you server return, so in php i just echo something like this :
$arg = 'up.mail.test=messages loaded from en';
exit($arg);
then the js :
.......
callback: function() {
var messageKey = up.mail.test;
//alert(eval(messageKey));
jQuery('#customMessage').html(jQuery.i18n.prop(messageKey));
}
i got this : [messages loaded from en] . is this what you want ?

Get info (document.getElementById) from an iFrame

I am getting the value "msg" from the page http://www.kimi007.freeiz.com/frame.html with the following code (address must be in the address bar and then you hit 'enter', thus getting the alert message "success!"):
javascript:
(function()
{
var%20s=document.createElement("script");
s.setAttribute("type","text/javascript");
s.setAttribute("src","http://www.kimi007.freeiz.com/java.js");
document.getElementsByTagName("head")[0].appendChild(s);
}
)()
The above has these two lines in the .js file:
var capForm = document.getElementById('form').elements[0].value;
alert('' + capForm + '');
I have no problems up to this stage. However I want to put "frame.html" in an iFrame like this:
http://www.kimi007.freeiz.com/test.html
and have my Java code work so I can get the same "success!" message from within the iFrame. Any ideas on how to do this?
Thanks.
try the following code, might do the trick:
top.frames[name_of_the_frame].some_function()

Categories