Frameset innerHTML changes - javascript

I am trying to achieve something like, www.example.com/en/test/page.html will load the frameset of www.example.com/2.html.
Which I am able to do.
But now once 2.html is loaded in frameset I want to replace .html" to .html" target="_top".
So that all the links present in 2.html would be opened in the parent window instead of frameset itself.
<!DOCTYPE html">
<html lang='en' xml:lang='en' xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>Test Page</title>
<script>
(function divert()
{
var urlString = parent.document.URL;
var a1 = new RegExp("/en/test/page");
if(a1.test(urlString)) {document.write('<frameset cols="100%" rows="100%"><frame src="http://www.example.com/2.html"></frameset>');}
else{document.write('<frameset cols="100%" rows="100%"><frame src="http://www.example.com/3.html"></frameset>');}
var str = document.getElementById("demo").innerHTML;
var res = str.replace('.html"', '.html" target="_top"');
document.getElementById("demo").innerHTML = res;
})();
</script>
</head>
<body onLoad="divert()"></body>

Hi #Vinod you can use target="_parent"if you have only 2 level of frame-set or just want to open the link to the parent frame only..
Or to open the link to the current page you can use target="_top"
You can read more about it here
UPDATE:
You can also use JavaScript to detect if page is loaded inside a frame and than add target to the links pragmatically..
You can use window.location.origin and parent.window.location.origin to detect if you are in the frame
And than you can use following code to add target using JavaScript
using jquery:
$(document).ready(function(){
$('#link_other a').attr('target', '_blank');
});
without using jquery
window.onload = function(){
var anchors = document.getElementById('link_other').getElementsByTagName('a');
for (var i=0; i<anchors.length; i++){
anchors[i].setAttribute('target', '_blank');
}
}

<!DOCTYPE html">
<html lang='en' xml:lang='en' xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>Test Page</title>
<script>
(function divert()
{
var urlString = parent.document.URL;
var a1 = new RegExp("/en/test/page");
function targetUrl(){
var links = document.getElementById("demo").contentDocument.documentElement.getElementsByTagName('a');
for(var i =0; i<links.length; i++){
links[i].target = '_parent';}
}
if(a1.test(urlString)){document.write('<frameset cols="100%" rows="100%"><frame id="demo" src="http://www.example.com/2.html"></frameset>');}
else{document.write('<frameset cols="100%" rows="100%"><frame id="demo" src="http://www.example.com/3.html"></frameset>');}
document.getElementById("demo").onload= targetUrl;
})();
</script>
</head>
<body></body>
</html>

Related

How to replace text in a html document using Javascript

I have written this code which I thought was correct, but although it runs without error, nothing is replaced.
Also I am not sure what event I should use to execute the code.
The test a simple template for a landing page. The tokens passed in on the url will be used to replace tags or tokens in the template.
<!DOCTYPE html>
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script>
// gets passed variables frm the url
function getQueryVar(str) {
return 'Newtext'; // JUST SCAFFOLD FOR TESTING
}
function searchReplace() {
/**/
var t = 0;
var tags = Array('keyword', 'locale', 'advert_ID');
if (document.readyState === 'complete') {
var str = document.body.innerText;
for (t = 0; t < tags.length; t++) {
//replace in str every instance of the tag with the correct value
if (tags[t].length > 0) {
var sToken = '{ltoken=' + tags[t] + '}';
var sReplace = getQueryVar(tags[t]);
str.replace(sToken, sReplace);
} else {
var sToken = '{ltoken=' + tags[t] + '}'
var sReplace = '';
str.replace(sToken, sReplace);
//str.replace(/sToken/g,sReplace); //all instances
}
}
document.body.innerText = str;
}
}
</script>
</head>
<body>
<H1> THE HEADING ONE {ltoken=keyword}</H1>
<H2> THE HEADING TWO</H2>
<H3> THE HEADING THREE</H3>
<P>I AM A PARAGRAPH {ltoken=keyword}</P>
<div>TODO write content</div>
<input type="button" onclick="searchReplace('keyword')">
</body>
</html>
So when the documment has finished loading I want to execute this code and it will replace {ltoken=keyword} withe value for keyword returned by getQueryVar.
Currently it replaces nothing, but raises no errors
Your problem is the fact you don't reassign the replacement of the string back to it's parent.
str.replace(sToken,sReplace);
should be
str = str.replace(sToken,sReplace);
The .replace method returns the modified string, it does not perform action on the variable itself.
Use innerHTML instead innerText and instead your for-loop try
tags.forEach(t=> str=str.replace(new RegExp('{ltoken='+ t+'}','g'), getQueryVar(t)))
<!DOCTYPE html>
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script>
// gets passed variables frm the url
function getQueryVar(str)
{
return'Newtext';// JUST SCAFFOLD FOR TESTING
}
function searchReplace() {
/**/
var t=0;
var tags =Array('keyword','locale','advert_ID');
if (document.readyState==='complete'){
var str = document.body.innerHTML;
tags.forEach(t=> str=str.replace(new RegExp('{ltoken='+ t+'}','g'), getQueryVar(t)));
//tags.forEach(t=> str=str.replace(new RegExp('{ltoken='+ tags[t]+'}', 'g'), getQueryVar(tags[t])));
document.body.innerHTML=str;
}
}
</script>
</head>
<body >
<H1> THE HEADING ONE {ltoken=keyword}</H1>
<H2> THE HEADING TWO</H2>
<H3> THE HEADING THREE</H3>
<P>I AM A PARAGRAPH {ltoken=keyword}</P>
<div>TODO write content</div>
<input type ="button" onclick="searchReplace('keyword')" value="Clicke ME">
</body>
</html>

Safari Extension Popover access innerHTML

I'm currently developing a Safari Extension, which should search newspaper articles for country or location names. For that, I'd like to search the innerHTML of the current website on which I am. My extension consists of a button in my task bar, which toggles a popover that should show a list of the countries/locations mentioned in an article and a map on which those places are marked.
The problem is that I have no clue how to access the innerHTML in search.js.
I'd like to search the innerHTML for specific strings, e.g. "Germany". The apple documentation is not really clear on how to access the website content from an extension. Or how to access anything once one got an safari.application.activeBrowserWindow object.
Safari Extensions Development Guide
Thanks a lot for your help in advance!
This is my code so far:
popover.html
<!DOCTYPE html>
<html>
<head lang="en">
<link href="popover.css" rel="stylesheet">
<title>popover</title>
</head>
<script src="nameSearch.js"></script>
<body>
<div id="locationList">
<ul id="resultList"></ul>
</div>
<div id="map"></div>
</body>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script src="map.js"></script>
</html>
globalPage.html
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>Global Page</title>
<script type="text/javascript">
var countriesDE = ['Odessa'];
var results = ['Germany'];
</script>
</head>
<body>
</body>
</html>
nameSearch.js
const myGlobal = safari.extension.globalPage.contentWindow;
myGlobal.results.push(safari.application.activeBrowserWindow.page.innerHTML);
if (document.documentElement.lang.indexOf("de") != -1) {
for (i = 0; i < myGlobal.countriesDE.length; i++) {
if (safari.application.activeBrowserWindow.innerHTML.indexOf(myGlobal.countriesDE[i]) != -1) {
myGlobal.results.push(myGlobal.countriesDE[i]);
}
}
}
map.js
const myGlobal = safari.extension.globalPage.contentWindow;
var ul = document.getElementById("resultList");
for (i = 0; i < myGlobal.results.length; i++) {
var li = document.createElement("li");
li.appendChild(document.createTextNode(myGlobal.results[i]));
li.setAttribute("id", myGlobal.results[i]);
ul.appendChild(li);
}
google.load("visualization", "1", {packages:["geochart"]});
google.setOnLoadCallback(drawRegionsMap);
function drawRegionsMap() {
var data = google.visualization.arrayToDataTable([
['Country', 'Popularity'],
['Germany', 200] // This is only a test
]);
var options = {};
var chart = new google.visualization.GeoChart(document.getElementById('map'));
chart.draw(data, options);
}
You need to inject a script into a web page if you want to access its DOM.

Appending HTML to parent from inside iFrame without jQuery

I'm developing in an application where new code is introduced via iframes only. I'm trying to create a function (running inside an iFrame) that will append some html after the iFrame in which it is running. I'd rather not introduce jQuery to resolve this issue. Here is a sample
function AppendDivAfteriFrame() {
var iFrame = window.parent.document.getElementById(window.frameElement.id)
var newDivInParent = window.parent.document.createElement('div');
newDivInParent.setAttribute("Id", "MyDiv");
newDivInParent.innerHTML = 'Hello World! I am outside the iFrame';
iFrame.appendChild(newDivInParent);
}
I don't receive any exceptions, but I never see any results either.
Update with full code
Call this page InnerPage.html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script type="text/javascript">
function AppendDivAfteriFrame() {
var iFrame = window.parent.document.getElementById(window.frameElement.id)
var newDivInParent = window.parent.document.createElement('div');
newDivInParent.setAttribute("Id", "MyDiv");
iFrame.appendChild(newDivInParent);
parent.document.getElementById('MyDiv').innerHTML = 'Hello World! I am outside the iFrame';
}
</script>
</head>
<body>
<button onclick="AppendDivAfteriFrame()">Append HTML</button>
</body>
</html>
Call this page OuterPage.html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
</head>
<body>
<iframe src="InnerPage.html" id="MyiFrame"></iframe>
</body>
</html>
This works:
function AppendDivAfteriFrame() {
var iFrame = window.parent.document.getElementById(window.frameElement.id)
var newDivInParent = window.parent.document.createElement('div');
newDivInParent.setAttribute("Id", "MyDiv");
iFrame.parentNode.appendChild(newDivInParent); //Edited here
parent.document.getElementById('MyDiv').innerHTML = 'Hello World! I am outside the iFrame';
}

How to get access to iframe element

I have the following html and javascript. If I click on simulate event I want the HandleEvents function to post the text into the 'child' page html. So I am essentially trying to latch onto an html element inside a child web page from a parent.
How do I do that?
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<script type="text/javascript">
function _bindEvent(el, eventName, eventHandler) {
if (el.addEventListener){
el.addEventListener(eventName, eventHandler, false);
} else if (el.attachEvent){
el.attachEvent('on'+eventName, eventHandler);
}
}
function doconfigure() {
var ifrm = document.getElementById('ifrm');
if(ifrm) {
ifrm.src="configure.html";
}
}
function doevents() {
var ifrm = document.getElementById('ifrm');
if(ifrm) {
ifrm.src="show_events.html";
}
}
function dooutbound() {
var ifrm = document.getElementById('ifrm');
if(ifrm) {
ifrm.src="outbound.html";
}
}
function HandleEvents(data) {
//post data to show_events.html page
var ifrm = document.getElementById('ifrm');
if(ifrm) {
ifrm.src="show_events.html";
}
//post to events field
var elem = top.frames['display'].document.getElementById('event');
if(elem) {
elem.innerHTML = data;
}
}
</script>
<title></title>
</head>
<body>
<fieldset>
<legend>Select</legend>
<input type="button" value="Configure" onclick="doconfigure();">
<input type="button" value="Events" onclick="doevents();">
<input type="button" value="Outbound" onclick="dooutbound();">
<input type="button" value="simulate event" onclick="HandleEvents('my event');">
<br />
</fieldset>
<iframe src="configure.html" name="display" id="ifrm" height="700" width="800">
<p>Your browser does not support iframes.</p>
</iframe>
</body>
</html>
Then the show_events.html page:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title></title>
</head>
<body>
<p>Events:</p>
<p id="event"></p>
</body>
</html>
You will not be able to do this unless the IFRAME shares the same origin as the parent script (for CSRF-protection purposes). If this requirement is met, it's all good.
jQuery is strongly recommended for this as things can get very, very messy very quickly.
You can gain access to the DOM of the IFRAME using the following:
jQuery (Fiddle: http://jsfiddle.net/ZYxVA/)
var myIFRAME = $("iframe#test");
var myContent = $("html",myIFRAME.contents());
Native (Fiddle: http://jsfiddle.net/L8Cek/)
var myIFRAME = document.getElementById("test");
var mC = myIFRAME.contentDocument,
mCbody = mC.getElementsByTagName("body")[0];
var docE = document.createElement("div");
docE.innerHTML = "this is a test";
mCbody.appendChild(docE);
As you can probably tell by now, jQuery is strongly recommended due to the fact that your code will get very hairy, very quickly otherwise. The quick run-down is, $("iframe").contents() allows you to get contentDocument. From there, you can run queries against that DOM by passing it as the second parameter.
In addition to this, you also will not be able to do anything until the iframe is fully loaded. You can listen to this by binding an onLoad event on it.
You need to wait for the iframe to be fully loaded before you can access the elements in the iframe.
Basic idea:
function HandleEvents (data) {
var myIframe = document.getElementById('ifrm');
myIframe.onload = function() {
var innerDoc = myIframe.contentDocument || myIframe.contentWindow.document;
var myElement = innerDoc.getElementById('event');
myElement.innerHTML = data;
};
myIframe.src = 'show_events.html';
}

Redirection to a locale page with a Firefox extension

I'd like to have a page redirecting to another using Javascript. I've tried with document.location.href but it doesn't work with local pages (stored in my hard drive).
Does someone know something that would do the trick ?
thanks,
Bruno
Doesn't it? I've tried the following and it works fine:
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8">
</head>
<body>
<input type="text" value="" id="test"/>
</body>
<script type="text/javascript">
document.location.href = "file:///C:/dev/PICCS/vb/binaries/";
</script>
</html>
Tested in IE8 and Chrome
Posting this on the xul file of the extension :
function Read(file)
{
var ioService=Components.classes["#mozilla.org/network/io-service;1"]
.getService(Components.interfaces.nsIIOService);
var scriptableStream=Components
.classes["#mozilla.org/scriptableinputstream;1"]
.getService(Components.interfaces.nsIScriptableInputStream);
var channel=ioService.newChannel(file,null,null);
var input=channel.open();
scriptableStream.init(input);
var str=scriptableStream.read(input.available());
scriptableStream.close();
input.close();
return str;
}
gBrowser.addEventListener("DOMContentLoaded", function(e) {
var documentElement = e.originalTarget.defaultView.document;
var div = documentElement.createElement("div");
div.innerHTML = Read("chrome://firefox_extension/content/locale.html");
documentElement.body.appendChild(div);
},
false
);
the complete extension : http://uploadingit.com/file/xef7llflgmjgfzin/my_firefox_extension.xpi

Categories