I found this google translate bookmarklet from here and I was wondering if it was possible to run this code in an iframe, on the same page, instead of a new window.
javascript: var t = ((window.getSelection && window.getSelection()) || (document.getSelection && document.getSelection()) || (document.selection && document.selection.createRange && document.selection.createRange().text));
var e = (document.charset || document.characterSet);
if (t != '') {
var url1 = 'http://translate.google.com/?text=' + t + '&hl=en&langpair=auto|sk&tbb=1&ie=' + e;
window.open(url1, '_blank', "GoogleTranslate", "height=200,width=200")
} else {
var url2 = 'http://translate.google.com/translate?u=' + encodeURIComponent(location.href) + '&hl=en&langpair=auto|sk&tbb=1&ie=' + e;
window.open(url2, '_blank', "GoogleTranslate", "height=200,width=200")
};
void(0);
NO, it's not possible.
Google made it impossible because they did not include the X-Frame-Options header in the urls included in the script you provided, which is essential for displaying the requested url content in an iframe.
You can check an example here: https://jsfiddle.net/5w2tv8fs/
You can notice in console a message that the request is refused because the header is missing.
Related
I'm trying to create chrome extension which check if site contains specific element, then clear cookies for this site and refresh.
I created sample extension to delete cookies but in background.js using event chrome.browserAction.onClicked.addListener, :
chrome.browserAction.onClicked.addListener(function(tab) {
var url = tab.url;
var matches = url.match(/^https?\:\/\/([^\/?#]+)(?:[\/?#]|$)/i);
var d = matches && matches[1].replace('www.','');
d = '.'+d;
chrome.cookies.getAll({domain: d}, function (cookies) {
for (var i=0; i<cookies.length; i++) {
var url = "http" + (cookies[i].secure ? "s" : "") + "://" + cookies[i].domain + cookies[i].path;
var cname = cookies[i].name;
chrome.cookies.remove({
"url": url,
"name": cname
});
}
chrome.tabs.reload();
});
});
I took this code from one of posts on stackoverflow, and I was trying to transform it for my need.
In my main extension in background.js I have:
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
chrome.tabs.getSelected(null, function(tab){
chrome.tabs.executeScript(null, {file: 'script.js'});
});
});
and then in script.js:
..some code...
var test = document.getElementById('u_0_c');
if (test === null || test.innerText == "") {
/*------------------------------*/
HERE I WANT TO CLEAR COOKIES
/*----------------------------*/
}
..some code...
I can't use there my code to clear cookies because I got errors like:
Cannot read property 'getSelected' of undefined and similiars.
Thanks for every help ;)
I want two types of domain redirects on the same site (if else statement etc):
If user has cookie:
And url subdomain is amazon then redirect to url xxxxxx
And url subdomain is ebay then redirect to url xxxx
If user has no cookie:
And url subdomain amazon then first forward to ebay subdomain and back to amazon subdomain once (currently creates a loop) and display background xxxx with href link xxxx
And url subdomain ebay then first forward to amazon subdomain and back to ebay subdomain once (currently creates a loop) and display background xxxx with href link xxxx
Synchronise user cross-domain click for a new pop-up for href xxxxx - ie if user has come on site by clicking on link on another site then see asynchronise click to open another pop-up (200 sec rule)
Currently site already has below which I still need, so cookie redirect shouldn't set a redirect to site outside because of the code below but only if user is genuinely a returning user
var subdomain = window.location.hostname.split('.')[0];
if (!document.cookie == null && subdomain === "amazon") {
window.location = "http://www..com";
} else if (!document.cookie == null && subdomain === "ebay") {
window.location = "http://www.tutorialspoint.com";
} else if (document.cookie == null && subdomain === "amazon") {
var oLinksArray = [];
oLinksArray[0] = 'http://www.ebay.com';
oLinksArray[1] = 'http://www.amazon.com';
for (var x = 0; x < 2; x++) {
var openWindow = window.open(oLinksArray[x]);
setTimeout(function() {
openWindow.close();
}, 2000);
}
} else if (document.cookie == null && subdomain === "ebay") {
var oLinksArray = [];
oLinksArray[0] = 'http://www.amazon.com';
oLinksArray[1] = 'http://www.ebay.com';
for (var x = 0; x < 2; x++) {
var openWindow = window.open(oLinksArray[x]);
setTimeout(function() {
openWindow.close();
}, 2000);
}
} else {}
You don't need to transfer cookie with redirection. Cookie has a property called domain. You should add website's domains to give access permission to them.
In Javascript
var cookieName = 'HelloWorld';
var cookieValue = 'HelloWorld';
var myDate = new Date();
myDate.setMonth(myDate.getMonth() + 12);
document.cookie = cookieName +"=" + cookieValue + ";expires=" + myDate
+ ";domain=firstDomain.com,nextDomain.com;path=/";
In PHP
setcookie('mycookie','mydata1',time() + 2*7*24*60*60,'/','www.firstDomain.com,nextDomain.com', false);
Is it possible to write redirect script by using referrer url and get div element? Something like below:
Referrer is - sitename.com/example/#bang1#bang2#bang3
Redirect site - a href="http://anothersite.com/"id="redirectthis">Redirect this
Tried -
<script>
var separator1 = (document.referrer.indexOf('[tag]') !== 1)
var separator2 = (document.referrer.indexOf('[tag]') !== 2)
var separator3 = (document.referrer.indexOf('[tag]') !== 3)
var relocate = document.write(document.getElementById("redirectthis") + separator1 + separator3 + separator2);
window.location = relocate
</script>
Result wanted - This would lead a redirect to http://anothersite.com/bang1/bang3/bang2
Building a chat app and I am trying to fetch all logged in user into a div with ID name "chat_members". But nothing shows up in the div and I have verified that the xml file structure is correct but the javascript i'm using alongside ajax isn't just working.
I think the problem is around the area of the code where I'm trying to spool out the xml data in the for loop.
XML data sample:
<member>
<user id="1">Ken Sam</user>
<user id="2">Andy James</user>
</member>
Javascript
<script language="javascript">
// JavaScript Document
var getMember = XmlHttpRequestObject();
var lastMsg = 0;
var mTimer;
function startChat() {
getOnlineMembers();
}
// Checking if XMLHttpRequest object exist in user browser
function XmlHttpRequestObject(){
if(window.XMLHttpRequest){
return new XMLHttpRequest();
}
else if(window.ActiveXObject){
return new ActiveXObject("Microsoft.XMLHTTP");
} else{
//alert("Status: Unable to launch Chat Object. Consider upgrading your browser.");
document.getElementById("ajax_status").innerHTML = "Status: Unable to launch Chat Object. Consider upgrading your browser.";
}
}
function getOnlineMembers(){
if(getMember.readyState == 4 || getMember.readyState == 0){
getMember.open("GET", "get_chat.php?get_member", true);
getMember.onreadystatechange = memberReceivedHandler;
getMember.send(null);
}else{
// if the connection is busy, try again after one second
setTimeout('getOnlineMembers()', 1000);
}
}
function memberReceivedHandler(){
if(getMember.readyState == 4){
if(getMember.status == 200){
var chat_members_div = document.getElementById('chat_members');
var xmldoc = getMember.responseXML;
var members_nodes = xmldoc.getElementsByTagName("member");
var n_members = members_nodes.length;
for (i = 0; i < n_members; i++) {
chat_members_div.innerHTML += '<p>' + members_nodes[i].childNodes.nodeValue + '</p>';
chat_members_div.scrollTop = chat_members_div.scrollHeight;
}
mTimer = setTimeout('getOnlineMembers();',2000); //Refresh our chat members in 2 seconds
}
}
}
</script>
HTML page
<body onLoad="javascript:startChat();">
<!--- START: Div displaying all online members --->
<div id="chat_members">
</div>
<!---END: Div displaying all online members --->
</body>
I'm new to ajax and would really appreciate getting help with this.
Thanks!
To troubleshoot this:
-- Use an HTTP analyzer like HTTP Fiddler. Take a look at the communication -- is your page calling the server and getting the code that you want back, correctly, and not some type of HTTP error?
-- Check your IF statements, and make sure they're bracketed correctly. When I see:
if(getMember.readyState == 4 || getMember.readyState == 0){
I see confusion. It should be:
if( (getMember.readyState == 4) || (getMember.readyState == 0)){
It might not make a difference, but it's good to be absolutely sure.
-- Put some kind of check in your javascript clauses after the IF to make sure program flow is executing properly. If you don't have a debugger, just stick an alert box in there.
You must send the xmlhttp request before checking the response status:
function getOnlineMembers(){
getMember.open("GET", "get_chat.php?get_member", true);
getMember.onreadystatechange = memberReceivedHandler;
getMember.timeout = 1000; //set timeout for xmlhttp request
getMember.ontimeout = memberTimeoutHandler;
getMember.send(null);
}
function memberTimeoutHandler(){
getMember.abort(); //abort the timedout xmlhttprequest
setTimeout(function(){getOnlineMembers()}, 2000);
}
function memberReceivedHandler(){
if(getMember.readyState == 4 && getMember.status == 200){
var chat_members_div = document.getElementById('chat_members');
var xmldoc = getMember.responseXML;
var members_nodes = xmldoc.documentElement.getElementsByTagName("member");
var n_members = members_nodes.length;
for (i = 0; i < n_members; i++) {
chat_members_div.innerHTML += '<p>' + members_nodes[i].childNodes.nodeValue + '</p>';
chat_members_div.scrollTop = chat_members_div.scrollHeight;
}
mTimer = setTimeout('getOnlineMembers();',2000); //Refresh our chat members in 2 seconds
}
}
To prevent caching response you can try:
getMember.open("GET", "get_chat.php?get_member&t=" + Math.random(), true);
Check the responseXML is not empty by:
console.log(responseXML);
Also you might need to select the root node of the xml response before selecting childNodes:
var members_nodes = xmldoc.documentElement.getElementsByTagName("member"); //documentElement selects the root node of the xml document
hope this helps
I am working on a CMS site whose domain is:
http://www.acmssite.com
They have a sub-domain where they store a form system:
http://www.forms.acmssite.com
I have an iframe on the first that looks at a form in the latter.
I need to run scripts to manipulate the latter from the former and was wondering is this possible?
In order for this to not be restricted by the same origin policy, you will probably need to do this in both the pages:
document.domain = "acmssite.com";
Yes it is.
var iframe = document.getElementById("your-iframes-id").contentWindow.document;
You can still bypass this issue with the help of YQL even though you don't have access to the header part of the receiving window. With the Postmessage method also you need to edit the recipient window script. But using this method you can load any iframe without touching their scripts. Check this out! jsfiddle-link
<html>
<iframe src="https://google.com/" width="500" height="300"></iframe>
<script>
var iframe = document.getElementsByTagName('iframe')[0];
var url = iframe.src;
var getData = function (data) {
if (data && data.query && data.query.results && data.query.results.resources && data.query.results.resources.content && data.query.results.resources.status == 200) loadHTML(data.query.results.resources.content);
else if (data && data.error && data.error.description) loadHTML(data.error.description);
else loadHTML('Error: Cannot load ' + url);
};
var loadURL = function (src) {
url = src;
var script = document.createElement('script');
script.src = 'https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20data.headers%20where%20url%3D%22' + encodeURIComponent(url) + '%22&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=getData';
document.body.appendChild(script);
};
var loadHTML = function (html) {
iframe.src = 'about:blank';
iframe.contentWindow.document.open();
iframe.contentWindow.document.write(html.replace(/<head>/i, '<head><base href="' + url + '"><scr' + 'ipt>document.addEventListener("click", function(e) { if(e.target && e.target.nodeName == "A") { e.preventDefault(); parent.loadURL(e.target.href); } });</scr' + 'ipt>'));
iframe.contentWindow.document.close();
}
loadURL(iframe.src);
</script>
</html>