Reputation: 217
I have a userscript that is dynamically loading an external javascript file and for some reason it is running twice.
Here is the code loading the file:
var jqScript = document.createElement('script');
jqScript.setAttribute('type', "text/javascript");
jqScript.setAttribute('src', "http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.2.js");
(document.body || document.head || document.documentElement).appendChild(jqScript);
var extraScript = document.createElement('script');
extraScript.setAttribute('src', "http://youtube.thegoblin.net/layoutFix/script.js");
document.body.appendChild(extraScript);
And the code from the external file:
alert(1);
$.get(
"http://www.youtube.com/my_subscriptions",
function(data) {
var dataSplit = data.split("<ol class=\"vm-vertical-nav\">")[1].split("</ol>")[0].split("<li>");
var dataString = [];
for (var i=2;i<dataSplit.length;i++)
{
dataString[i - 2] = dataSplit[i].split(">")[1].split("</a")[0];
}
alert(dataString);
}
, "text");
When I run my code I get both alerts from the external .js file, but I get them twice.
What have I done? How can I make them only be called once?
UPDATE:
How can I only append it to the current page and not the iframes as well?
Upvotes: 3
Views: 3468
Reputation: 1074385
I think what's happening is that your userscript doing the append is being applied to all windows (the main one, and the iframes), not that your code doing the append inadvertently appends to the iframes as well as the main window. E.g., your append code is being run for the main window and for each iframe.
There are a couple of ways to know whether you're in an iframe. One is to check for window.frameElement
being !null
. So:
if (!window.frameElement) {
// ...your append code here...
}
According to MDN, that will work with just about any version of IE, any version of Firefox, and Chrome 18 or higher.
Another way to check is to see if window.top
!= window.self
, so:
if (window.top != window.self) {
// ...your append code here...
}
Upvotes: 2