Inserting code from Contentscript.js (Chrome Extension) - javascript

I am Developing the Politics & Information Google Chrome Extension but I have run into a problem, I am attempting to insert a JS Script into one of the div's of the Webpage, the result is nothing, absolutely nothing pops up
I know i have the right area because if I use += "Hello"; it displays the text there properly, but when I actually do +="" the script doesn't seem to run. To all them devs out there, any suggestions?
How I am doing it:
theinfotable.children[0].innerHTML += '';
JavaScript (Google Chrome Extension inserted from the Contentscripts.js file)
I can see that the Code Inserted, but the script still doesn't seem to load: (And I know this code works when I have my own page instead of inserting)
http://oi61.tinypic.com/2irkx9c.jpg

Rather than use .innerHTML, have you tried creating a new element and appending it?
var injectable = document.createElement("script");
injectable.innerHTML = "console.log('Injected!');" // Your script here
// or injectable.src = "location" if you'd rather link
theinfotable.children[0].appendChild(injectable);
I'm not entirely sure why this occurs, if I had to guess it's an idiosyncrasy in how things are parsed or a security measure, but appendChild should do the trick. Basically, from what I understand it's the difference between
innerHTML +=: converting HTML to a string, and adding to that string, and re-parsing that string with new content
and...
appendChild: creating a DOM node, appending said DOM node, recalculating/refreshing the document for styling recalculations.
And somewhere in the parsing, your new script info is ignored.

I figured out the problem, the page was blocking my script as "Insecure" at the top right there was a little Shield Icon and after clicking on it I just had to put "Show Insecure Scripts" and it popped up.
(If anyone feels like telling me so people don't have to do this, that'd be great :D) I would rather people just have it pop up instead of having to stay for it to pop up

Related

How to set the encoding of an embedded text iframe

I am here asking about document embedding in HTML.
In a project I am working on, I am embedding my update logs as text files directly into my page, with a selection menu to view all the different updates.
The problem I am having, is not really much of a problem, being that they are plain text files, but the Firefox (have not tested elsewhere yet) console spits out a "No character encoding in the iframe document" warning.
I have searched far and wide for a solution to this problem, only to find that every solution is specifically main-level document based, like "put a tag in the html header", which I already have done from the start. I just use this:
<embed id="update_display" src="some_latest_update_file.txt" />
The embed seems to create an iframe, with the text file as the source. This works fine for me, where I am just displaying the updates. But what I am trying to control is the warning, I don't want to see the warning for something stupid like that. I know I can display my updates differently, but I would like to keep the current method if possible.
Is there a way to set the encoding of the iframe, without actually knowing the id or anything about what the embed will create?
It creates an entirely different document within my document, with it's own html, head, body and such tags. I would greatly appreciate any answer for this, as I want to keep my console clean and warning/error free.
I never actually ended up sticking with this, I just used <object src='somefile'></object> instead and included the encoding in the source file.

How to find which script modifies css of selected attribute

Is there a way to get information which scripts modified selected DOM element, and in which order?
On my website, I modify width of div A. It appears however, that some other script modifies that width after that, but I do not know which script it is. How can I find it?
Edit:
After searching a bit more, I fount that in firebug you can right click attribute in HTML view, and select "stop javascript on change" (or sth similar, my firefox is not in english), the problem being it resets after reloading the page, what makes it useles for me.
I am using chrome developer tools to debug my page. It supports add breakpoints to dom elements, when attributes of dom is modified by javascript, it breaks the rendering process immediately. I think you can try it.

How to detect where JavaScript alert is coming from?

I am trying to debug a very complex IE Intranet application. I am getting an alert with a custom message stating that an exception has occurred. I would like to find out more information about this exception as the message is not very helpful.
There is a master page which contains a lot of iFrames (and .htc files if that makes a difference) so I don't think that I can try and hijack window.alert. My last resort will be to try my luck with a file search.
Using IE 8, is there anyway I can detect where this alert is coming from? The ideal solution would be to somehow create a "breakOnAlert" function which inserts a debbuger statement at the correct alert location.
To clarify: The master page contains many iframes and I believe that the error+alert is coming from one of these. Each iframe is an aspx page (sometimes with dynamic html/javascript from the user) and contains inline and external JavaScript. Before posting I did try overriding alert in my page (a child page inside an iframe) but it didn't work. I am assuming that It doesn't work as each iframe has their own window object so they each have their own version of alert. For this to work I would need to find all iframes and override it for each one, something which I think would be very complicated to do. In the IE developer tools I can see a huge amount of script files (inline and external), so it would be very difficult to manually look for the alerts in there.
Since it's a real chore to do it in all iframes, I'd probably use Fiddler and programatically replace alert( with something like:
(function(n){alert(n);debugger;})(
IE should support the debugger statement, so you'd have a call-stack
This page explains how to do a text-replace in Fiddler
Example Fiddler custom rule to add to OnBeforeResponse:
if (oSession.oResponse.headers.ExistsAndContains("Content-Type", "html"))
{
oSession.utilDecodeResponse();
var oBody = System.Text.Encoding.UTF8.GetString(oSession.responseBodyBytes);
oBody = oBody.replace(/alert\(/gi, "(function(n){alert(n);debugger;})(");
oSession.utilSetResponseBody(oBody);
}
Ovveride alert function and set a breakpoint inside, then you can watch Stack Trace :)
function alert(message) {
var x = 'whatever';
}
$(function () {
alert('test');
});

Has Chrome browser broken dynamic script loading?

This isn't my code, I'm just troubleshooting it. Some code that has been working for over a year has now stopped working in Chrome (12.0.742.122), but works in the other "big" browsers (including fellow WebKit stablemate Safari (5.0.5)). By "not working anymore" I mean that although the script file does load, it doesn't execute. The kind of behaviour you'd expect if loading a script into innerHTML or writing it into a div, but neither of which things are being done. The commented-out lines below were all failed attempts at getting it working, the first of those being the original code that had worked up until recently.
<div id="abc"></div>
<script type="text/javascript">
var d=document.getElementById("abc");
var s=document.createElement('SCRIPT');
if(s){s.src=script_path;}
//if(d)d.appendChild(s); //original line that still works in all other browsers
//if(d)d.parentNode.appendChild(s);
//if(d)d.parentNode.insertBefore(s,d);
//if(d)d.parentNode.insertBefore(s,d.nextSibling);
document.body.appendChild(s); //this works, script executes
</script>
What is wanted from this code above, is that the script is a child of the div. Presumably they want to be able to remove that child and have all script be removed at the same time (I'm not sure of their motivation).
I've discovered what the problem was, largely thanks to Martin Bieder's back and forth and introducing me to jsfiddle.net with his working example.
The issue was actually the test page and what you'd think would be a fairly harmless error they made in creating it. The div and all of the code will be represented below simply as ######, as it's not even relevant to the problem. It's actually a HTML problem. Chrome 12 isn't happy if you don't match up your closing tags properly. I really can't believe that it has an effect on the execution on script files, but it does. I've tried many many times in the last 10 minutes with the HTML tags right and wrong and unbelievably this really is the problem.
<font><center><b>
##########
</b></font></center>
You see how the font and center closing tags are the wrong way around, and that's enough to confuse Chrome sufficiently that it won't execute any dynamic script being added within those tags. Bizarre. I can't recreate this on jsfiddle, probably due to the nature of the site runs the html/js that you put onto it (using onload for example).
No it works. Google Analytics uses is, too.
var ga=document.createElement('script');
ga.type='text/javascript';
ga.async=true;
ga.src='http://www.google-analytics.com/ga.js';
var s=document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(ga,s);
Have you tried to set to async the script element?
var script = document.createElement('script');
script.async = 'async';
It is all about 3 things.. Organization, Optimization, and debugging.
1)properly scoping your tags makes things easier to read.
2)properly organizing your code makes it easier to parse which means parsers can be faster and more efficient.
3)alot of the debug tools we use rely on this organization in order to display things like collapsible tags and present a more visual scoping

How do I create a Toolbar/ Bookmarklet using Javascript?

Hi i'm a JavaScript novice and need some help. I am trying to create a toolbar which can be viewed on any website through the use of a bookmarklet, the toolbar is simply just a div with a few links. But i am stuck on how to achieve this. Any help to accomplish this would be greatly appreciated.
most bookmarklets that do something complecated like "creating a toolbar" simply add an external script to the page that the bookmarklet is invoked on.
Basically all you have to do is write a link that contains javascript, which can be acheived by starting the href="" with javascript:
so lets just start with a script in an href that will add an external JavaScript to your page
addScript = function ( url ) {
myScript = document.createElement('script');
myScript.src = "url";
document.head.appendChild(myScript);
};
addScript("http://google.com/");
so if you shrink that down into a url you get..
click to add toolbar
however you want to make this bookmark-able so theres one more level of confusion we have to add... and this part has to be done in different ways depending on the browser
addBookmark( url, title ) {
if (window.sidebar) { // Firefox
window.sidebar.addPanel(url,bookmarkName,"");
} else if(window.external) { // IE
window.external.AddFavorite(url,bookmarkName);
}
}
You can include that on the page where you're going to have your add bookmark button. A couple things to note though
this isnt going to work in opera.. but who cares about opera
webkit browsers (chrome & safari) dont allow javascript to create bookmarklets
Finally you need to mash it all up into one ugly link
click to add bookmark
In the end though I suggest you look into making a Google Chrome Extension or a Firefox Plugin instead of a bookmarklet since you have more capability with either of the two.
As far as how to make a toolbar with JavaScript, well you're just going to have to make another question for that.. Its too much and you haven said enough about what you wan to do for me to answer it here.
bombedmetor,
Greg Guida's tip on including an external script will allow you to create an awesome, clean bookmarklet-based toolbar. Why? Because you'll be able to use JavaScript libraries like JQuery, etc.
Here's a quick example along the lines you asked for to help get you started. The bookmarklet creates a div element with a link to the Stack Overflow homepage.
javascript:void(function(){var divElmt=document.createElement('div');link1=document.createElement('a'); link1.href='http://stackoverflow.com';link1.innerHTML='StackOverflow Homepage';divElmt.style.backgroundColor='yellow';divElmt.style.position='fixed';divElmt.style.top='0px';divElmt.style.width='10em';divElmt.style.height='5em'; divElmt.style.border='solid red 4px';divElmt.style.zIndex='100'; divElmt.appendChild(link1);document.body.appendChild(divElmt);})();
To use the above bookmarklet, you create a new bookmark in your favorite browser and add the code above where you would normally place the URL.
The code does the following:
Creates a new div element.
Creates a new anchor element and sets the value of the href attribute.
Assigns some basic values to the style attributes of the new div (so you can see it easily).
Appends the anchor as a child element of the new div.
Appends the new div element as a child of the body element.
If all goes well, you should see a yellow box with a link to the Stack Overflow homepage at the top-right of your page after using the bookmarklet. bombedmetor - I hope this helps get you started. After you get comfortable with how these things work, you can apply Greg's wisdom to create your toolbar bookmarklet in a way that can be added to people's browsers with just a click or two.
Something to keep in mind: As Greg indicates, bookmarklet code is treated as the contents of the href attribute of an anchor element. This is why I used single quotes in the code above.
Some sites/articles to check out:
http://en.wikipedia.org/wiki/Bookmarklets
http://www.latentmotion.com/how-to-create-a-jquery-bookmarklet/

Categories