Getting an Odd Error using Javascript/jQuery - javascript

Trying to select the following link in html:
Nodequeue
with this Javascript:
jQuery("a:contains('Nodequeue')").trigger("click");
And I am receiving this error message:
Javascript console (:1): Unsafe JavaScript attempt to access frame with URL http://cdn.nprove.com/cpma/p/1/2/e/b/12ebf3bc368ry3ra.html?npuid=1310010225&rurl=&id=cpma-2n7eypbvio581300288437193&null=&r=366424962878227 from frame with URL http://www.benzinga.com/analyst-ratings/analyst-color/11/07/1742957/the-beef-stops-here. Domains, protocols and ports must match.
Any idea what might cause this?

I created a
JSFiddle of your code which you can look at and notice that in the console your error doesn't come up in Chrome 12 or FireFox 5. I'm not sure what version of jQuery you are using that is causing that or your DOM situation that may be triggering that error, however, try this potential fix:
(function(window, $) {
$.fn.triggerAnchor = function() {
return this.each(function(e) {
var href = $(this).attr('href');
window.location.href = href;
return false;
});
};
})(this, this.jQuery);
Then use with:
$("a:contains('Nodequeue')").triggerAnchor();
I don't think jQuery triggers anchors, and it certaintly doesn't trigger native click events. This is the closest thing I can think of to emulate that behavior.
You can see it 'working' here
Explanation of the code:
The code is simply a jQuery plugin that looks at the href attribute of anchor and sets the window location to that value. I wrote in the typical pattern of a wrapped closure to localize references to window and jQuery. I'm allowing you to call this on multiple anchors, but I'm assuming the average user would only need to run this once.

That error usually means you are making a javascript request from one frame to another. In this case, is the link in an iframe, or is jquery running in an iframe?

Related

jQuery on external text requesting images

I'm working on a chrome extension that uses jquery to parse the source of a page for specific things. In example I'm looking through Wikipedia to get the categories.
I get the source of the page via
chrome.tabs.executeScript(tabId, {
code: "chrome.extension.sendMessage({action: 'getContentText', source: document.body.innerHTML, location: window.location});"
}, function() {
if (chrome.extension.lastError)
console.log(chrome.extension.lastError.message);
});
I am then listening for this message (successfully) and then use jquery to parse the source key of the object, like so
if (request.action == "getContentText")
{
//console.log(request.source);
$('#mw-normal-catlinks > ul > li > a', request.source).each(function()
{
console.log("category", $(this).html());
});
}
This works as expected and logs a list of all the category links innerHTML. However the issue happens from that jQuery selector that it tries to load the images that are contained in request.source. This results in errors such as
GET chrome-extension://upload.wikimedia.org/wikipedia/commons/thumb/f/fc/Padlock-silver.svg/20px-Padlock-silver.svg.png net::ERR_FAILED
These are valid links, however they are being called (unneeded) from my extension with the chrome-extension:// prefix (which is invalid). I'm not sure why jquery would try to evaluate/request images from within source using a selector
I guess this is happening because Wikipedia uses relative paths on their images (instead of https:// or http://, simply // - so the content loaded is relative to the server). The requests are being made by jQuery and you can see here how to fix this issue (in future, please make sure to search SO more thoroughly).
A huge thank you to #timonwimmer for helping me in the chat. We both happened to find different solutions at the same time.
My solution was to use a regex to remove any occurances of the images. Via
var source = request.source.replace(/.*?\.wikimedia\.org\/.*?/g, "");
His was an answer on stack overflow already, that was derived from another answer. If you are interested this answer works perfectly
If you give jQuery a string with a complete element declaration it actually generates a new DOM element, similar to calling document.createElement(tagName) and setting all of the attributes.
For instance: var $newEl = $("<p>test</p>") or in your case img tag elements with $("<img/>"). That would get parsed and created as a new DOM HTML element and wrapped by jQuery so you can query it.
Since you are passing a complete and valid HTML string, it is parsing it into an actual DOM first. This is because jQuery uses the built in underlying document.querySelector methods and they act on the DOM not on strings -- think of the DOM as a database with indexes for id and class and attributes for querying. For instance, MongoDB cannot perform queries on a raw JSON string, it needs to first process the JSON into BSON and index it all and the queries are performed on that.
Your problem is less with jQuery and more so with how elements are created and what happens when attributes change for those elements. For instance, when the img elements are created with document.createElement('img') and then the src attribute is set with imgElement.src = "link to image" this automatically triggers the load for the image at location src.
You can test this out for yourself by running this in your JavaScript Developer Console:
var img = document.createElement('img');
img.src = "broken-link";
Notice that this will likely show and errors in your console after running stating that the image cannot be found.
So what you want, to ensure so it does not resolve the image's src, is to either
1) apply jQuery on an existing DOM (document.body, etc), or
2) let it parse and evaluate the string into a DOM and clean the string before hand (remove the img tags using Regex or something). Take a look at https://stackoverflow.com/a/11230103/2578205 for removing HTML tags from string.
Hope it works out!

Why does this simple login script work in Tampermonkey but not Greasemonkey?

I have this tiny little script that I run inside Chrome using Tampermonkey and works great.
However, when I use it in Firefox with Greasemonkey, it shows up on the active list, meaning its matching the page but it doesn't actually execute the code. I know it has to be a simple something I am overlooking but its not hitting me.
var myVar=setInterval(function(){myTimer();},100);
function myStopFunction()
{
clearInterval(myVar);
}
function myTimer()
{
var p1 = "Login";
var p2 = "mode=login";
var x = document.body.innerHTML;
if (x.match(p1) && x.match(p2)){
document.documentURI = "/ucp.php?mode=login";
}
myStopFunction();
}
Script Logic/Function
I am using a timer to prevent the script from triggering over and over in a permanent loop.
It simply detects if I am logged into a phpBB forum or not, if not send me to the login page so I can log in.
I am using document URI so that the location of the original is preserved so upon login, it takes me right back to it.
Often phpBB when you log in, it will take you back to the index page so this preserves my original intent of going to the actual link.
This script works perfectly and as expected on Chrome using TM but on Firefox using GM it doesn't trigger, am I missing something here?
From the Firefox spec:
(document.documentURI)
Returns the document location as string. It is read-only per DOM4 specification.
And, indeed, the latest spec still specifies that this attribute must be read only.
If Chrome lets you write this property, then that is non-standard behavior and maybe a bug.
Use location.assign(), or location.replace(), or just programmatically click the login button -- which often preserves the target page.

window.open not working in IE

Apparently, this call to window.open is not valid under Internet Explorer. The Javascript code on my site is not running, I would assume it is due to that error.
The line it tells me the error is on, is the call to window.open, apparently an argument is not valid there.
$('.objeto').click(
function() {
var center = 'height=380,width=900,top='+((screen.width - 900)/2)+',left='+((screen.height - 380)/2);
var address = $(this).attr('id');
window.open (address,'Ver articulo', config=center);
}
);
The site runs fine under both Google Chrome, and Firefox.
In IE, you can't have spaces in your second variable (the new window's name).
Try:
window.open (address,'Ver_articulo', config=center);
Also worth re-iterating that IE9 (and possibly below) doesn't like hyphens ('-') in the window name (2nd parameter).
I know one of the comments mentioned this, but it's a bit buried - and it's one tip that just solved an issue for me.
I'm not sure what config is, you just need:
window.open (address,'VerArticulo', center);
Keep in mind though, it looks like your id attribute is invalid to get the effect here, you probably want to use something different, e.g. data-href="urlHere" on the element, if it's not an anchor already.
even thou it's kind a late with answer for OP, but for someone else stumbling across this post it might help:
Had exactly same problem as OP after trying to use "window.open" method. It turns out that Chrome is ok with original href tag with URL in it where IE seems to get confused with that. After removing href from link worked spot on.
CODE SAMPLE:
$(document).ready(function ()
{
$('a[rel^="external"]').each(function ()
{
var externalLink = $(this);
var externalLinkValue = externalLink.attr("href");
externalLink.unbind('click');
externalLink.removeAttr("href");
externalLink.click(function (event)
{
event.preventDefault();
followExtrenalLink = window.open(externalLinkValue,'_blank');
});
externalLink.hover(function ()
{
externalLink.css('cursor', 'pointer');
});
});

How to code firefox extension which run javascript code in the page's context like firebug does

I know that for safety reasons that this is not easy to achieve, however there would be a way to do so as firebug does...
Please help, would like to invoke some script in the page's context to achieve some effect...
Basically, I would like to achieve two functionality:
1. add jQuery to any web page automatically if not already exist.
2. when open certain address, call a method of that page to auto notify the server. (an ajax functionality of the page)
I have tried to inject on the body, no luck.
tried to get the window object, which however do not have access to call the function.
Will try to change the location to something like: javascript:alert('test inject');
Many thx.
OK, after reading some official documentation and the GreaseMonkey's source, I get the following method which basically works for me.
Hope it will save sb's hour:
var appcontent = document.getElementById("appcontent"); // browser
if (appcontent) {
appcontent.addEventListener("DOMContentLoaded", function (evnt) {
var doc = evnt.originalTarget;
var win = doc.defaultView;
var unsafeWin = win.wrappedJSObject;
// vote.up is the function on the page's context
// which is take from this site as example
unsafeWin.vote.up(...);
}, true);
}
}
Greasemonkey does that. If you are developing your own extension with similar functionality, you can use Components.utils.evalInSandbox.

Opener.Location.Reload(); displayed Permission denied error in java script

I had two domains for ex. domain1 and domain2, I am opening domain2/index.aspx page as popup from domain1/default.aspx page. While closing domain2 page i need to reload the domain1 page, i had given the javascript code as "Opener.Location.Reload();". I am getting Permission denied javascript error. Any ideas about this issue.
I found that setting a parentUrl variable in the popup window (gotten from a query string)
and then using :
window.opener.location.href = parentUrl;
works.
I don't know why, I think it's magic, but it works (tested on IE, chrome and Firefox).
You cannot read the value of window.opener.location.href, but you can set it to whatever url you want. I use this oddity to do the refresh.
Hope it helps
Certain properties and actions are specifically blocked in cross-domain scenarios. What you might be able to do is create a function on the parent that does the code you want, then call that function from the child.
Example:
// On the parent...
function DoTheRefresh()
{
location.reload();
}
Then, on the child:
opener.DoTheRefresh();
I have done this in the past, so I don't know for sure if it's still an option. I hope it works out for you :)
You can accomplish this by putting code in the parent window to detect when the child window has closed.
var win2;
function openWindow()
{
win2 = window.open('http://...','childwindow',...);
checkChild();
}
function checkChild() {
if (win2.closed) {
window.location.reload(true);
} else setTimeout("checkChild()",1);
}

Categories