Prevent user to click on browsers back button Angular2 - browser

I am working with Angular 2 JS with Typescript. I have a requirement where I don't want to click/navigate to previous page via Browsers back button.
So how we can disable or prevent user to click or move to previous page via browser.
I have tried some example which are available over internet but those are not working properly. Like -
this.router.navigate(['/view'], { replaceUrl: true });
or
this.router.navigate(['/view'], { skipLocationChange: true });

Use this on page load, it will stop user on navigating back from page on which it placed.
put the code as it is in index.html page of the angular
<script type = "text/javascript">
function changeHashOnLoad() {
window.location.href += "#";
setTimeout("changeHashAgain()", "50");
}
function changeHashAgain()
{
window.location.href += "1";
}
var storedHash = window.location.hash;
window.setInterval(function () {
if (window.location.hash != storedHash) {
window.location.hash = storedHash;
}
}, 50);
</script>

Related

Unable to get the elements of an iframe using phantomJS

I am searching for a way to get the control on the elements inside a document. The problem is, the document is attached to an iFrame.
Here's an example:
.goto('https://wirecard-sandbox-engine.thesolution.com/engine/hpp/')
.use(iframe.withFrameName('wc', function (nightmare) {
nightmare
.type('#account_number', accountNumber)
.screenshot(resultfolder + '\\06-Card-Number.png')
.type('#card_security_code', testData.securityCode)
.selectIndex('#expiration_month_list', 1)
.selectIndex('#expiration_year_list', 4)
.click('span[id="hpp-form-submit"]')
}))
What I am trying to do above is:
Getting the iFrame with the Url.
Using this to get the control on every element in iFrame.
I encountered a similar issue. For one reason or another (Windows? Outdated?) the package nightmare-iframe was not working for me.
So I did this using pure DOM, which would transcribe for you:
var info = {
"account": account_number,
"security": testData.security_code;
};
nightmare.wait( () => {
/* Return true when the iframe is loaded */
var iframe = document.querySelector("iframe[name='wc']");
if (!iframe) {
return false;
}
var iframeDocument = iframe.contentDocument || iframe.contentWindow.document;
return iframeDocument.querySelector("#account_number") != null;
}).evaluate( (info) => {
var iframe = document.querySelector("iframe[name='wc']");
var iframeDocument = iframe.contentDocument || iframe.contentWindow.document;
iframeDocument.querySelector("#account_number").value = info.account;
iframeDocument.querySelector("#card_security_code").value = info.security;
//also use DOM to set proper date
...
iframeDocument.querySelector("span#hpp-form-submit").click();
}, info).then( () => {
console.log("submit done!");
}).catch((error) => {
console.error("Error in iframe magic", error);
});
This only works of course if the iframe is in the same domain as the main page and same-origin is allowed for the iframe. My use case was logging into paypal from a merchant's page.
For iframes with different origin, nightmare-iframe would be the package to use but then an error is needed to see what's the problem.

Chrome extension: match opened tab to loaded tab in background.js

I have a Chrome extension. I need to pass a variable to the tab that is opened, and then have that variable be available when the tab's webpage has completed loading. I need to be able to uniquely match the opened tab with the loaded tab.
chrome.browserAction.onClicked.addListener(function(tab) {
url = "my_url";
unique_id = "some id"; // I need to pass this on
chrome.tabs.create({ url: url }, function(tab){});
// I cannot use any global vars because this function actually loops and opens lots of tabs.
});
// Called when page has finished loading
chrome.webNavigation.onCompleted.addListener(function(tab) {
if(tab.frameId == 0){
// I need to identify the tab (unique_id) that was created in chrome.browserAction.onClicked.addListener()
// tab.url won't work because it's different if the orginal url was redirected
}
});
Tabs have tab IDs which are unique within a browser session.
chrome.browserAction.onClicked.addListener(function(tab) {
url = "my_url";
chrome.tabs.create({ url: url }, function(tab){
unique_id = tab.id; // I need to pass this on
});
});
// Called when page has finished loading
chrome.webNavigation.onCompleted.addListener(function(details) {
if(details.frameId == 0){
unique_id = details.tabId;
}
});

Chrome/FF/Safari extension: Load hidden web page in incognito-like mode

Is it possible to build an 'incognito mode' for loading background web-pages in a browser extension?
I am writing a non-IE cross-browser extension that periodically checks web-pages on the user's behalf. There are two requirements:
Page checks are done in the background, to be as unobtrusive as possible. I believe this could be done by opening the page in a new unfocussed browser tab, or hidden in a sandboxed iframe in the extension's background page.
The page checks should operate in 'incognito mode', and not use/update the user's cookies, history, or local storage. This is to stop the checks polluting the user's actual browsing behavior as much as possible.
Any thoughts on how to implement this 'incognito mode'?
It would ideally work in as many browser types as possible (not IE).
My current ideas are:
Filter out cookie headers from incoming/outgoing http requests associated with the page checks (if I can identify all of these) (not possible in Safari?)
After each page check, filter out the page from the user's history.
Useful SO questions I've found:
Chrome extension: loading a hidden page (without iframe)
Firefox addon development, open a hidden web browser
Identify requests originating in the hiddenDOMWindow (or one of its iframes)
var Cu = Components.utils;
Cu.import('resource://gre/modules/Services.jsm');
Cu.import('resource://gre/modules/devtools/Console.jsm');
var win = Services.appShell.hiddenDOMWindow
var iframe = win.document.createElementNS('http://www.w3.org/1999/xhtml', 'iframe');
iframe.addEventListener('DOMContentLoaded', function(e) {
var win = e.originalTarget.defaultView;
console.log('done loaded', e.document.location);
if (win.frameElement && win.frameElement != iframe) {
//its a frame in the in iframe that load
}
}, false);
win.document.documentElement.appendChild(iframe);
must keep a global var reference to iframe we added.
then you can change the iframe location like this, and when its loaded it triggers the event listener above
iframe.contentWindow.location = 'http://www.bing.com/'
that DOMContentLoaded identifies all things loaded in that iframe. if the page has frames it detects that too.
to remove from history, into the DOMContentLoaded function use the history service to remove win.location from history:
https://developer.mozilla.org/en-US/docs/Using_the_Places_history_service
now to strip the cookies from requests in that page use this code:
const {classes: Cc, Constructor: CC, interfaces: Ci, utils: Cu, results: Cr, manager: Cm} = Components;
Cu.import('resource://gre/modules/Services.jsm');
var myTabToSpoofIn = Services.wm.getMostRecentBrowser('navigator:browser').gBrowser.tabContainer[0]; //will spoof in the first tab of your browser
var httpRequestObserver = {
observe: function (subject, topic, data) {
var httpChannel, requestURL;
if (topic == "http-on-modify-request") {
httpChannel = subject.QueryInterface(Ci.nsIHttpChannel);
var goodies = loadContextGoodies(httpChannel)
if (goodies) {
if (goodies.contentWindow.top == iframe.contentWindow.top) {
httpChannel.setRequestHeader('Cookie', '', false);
} else {
//this page load isnt in our iframe so ignore it
}
}
}
}
};
Services.obs.addObserver(httpRequestObserver, "http-on-modify-request", false);
//Services.obs.removeObserver(httpRequestObserver, "http-on-modify-request", false); //run this on shudown of your addon otherwise the observer stags registerd
//this function gets the contentWindow and other good stuff from loadContext of httpChannel
function loadContextGoodies(httpChannel) {
//httpChannel must be the subject of http-on-modify-request QI'ed to nsiHTTPChannel as is done on line 8 "httpChannel = subject.QueryInterface(Ci.nsIHttpChannel);"
//start loadContext stuff
var loadContext;
try {
var interfaceRequestor = httpChannel.notificationCallbacks.QueryInterface(Ci.nsIInterfaceRequestor);
//var DOMWindow = interfaceRequestor.getInterface(Components.interfaces.nsIDOMWindow); //not to be done anymore because: https://developer.mozilla.org/en-US/docs/Updating_extensions_for_Firefox_3.5#Getting_a_load_context_from_a_request //instead do the loadContext stuff below
try {
loadContext = interfaceRequestor.getInterface(Ci.nsILoadContext);
} catch (ex) {
try {
loadContext = subject.loadGroup.notificationCallbacks.getInterface(Ci.nsILoadContext);
} catch (ex2) {}
}
} catch (ex0) {}
if (!loadContext) {
//no load context so dont do anything although you can run this, which is your old code
//this probably means that its loading an ajax call or like a google ad thing
return null;
} else {
var contentWindow = loadContext.associatedWindow;
if (!contentWindow) {
//this channel does not have a window, its probably loading a resource
//this probably means that its loading an ajax call or like a google ad thing
return null;
} else {
var aDOMWindow = contentWindow.top.QueryInterface(Ci.nsIInterfaceRequestor)
.getInterface(Ci.nsIWebNavigation)
.QueryInterface(Ci.nsIDocShellTreeItem)
.rootTreeItem
.QueryInterface(Ci.nsIInterfaceRequestor)
.getInterface(Ci.nsIDOMWindow);
var gBrowser = aDOMWindow.gBrowser;
var aTab = gBrowser._getTabForContentWindow(contentWindow.top); //this is the clickable tab xul element, the one found in the tab strip of the firefox window, aTab.linkedBrowser is same as browser var above //can stylize tab like aTab.style.backgroundColor = 'blue'; //can stylize the tab like aTab.style.fontColor = 'red';
var browser = aTab.linkedBrowser; //this is the browser within the tab //this is where the example in the previous section ends
return {
aDOMWindow: aDOMWindow,
gBrowser: gBrowser,
aTab: aTab,
browser: browser,
contentWindow: contentWindow
};
}
}
//end loadContext stuff
}

getting the current url from chrome extension

i'm making a chrome extension that opens a web-site if the current tab is not the same web-site, so i managed to get all of the tabs like this:
chrome.tabs.getAllInWindow(null, allTabs);
and i wrote a function to display it:
function allTabs(tabs) {
var tabsURLS = '';
for (var i = 0; i < tabs.length; i++) {
tabsURLS = tabs[i].url + '\n';
}
alert(tabsURLS);
}
but i need to get the current page url so i get the current tab by this:
var object=chrome.tabs.getCurrent(function(){;});
but i cant get to page properties like id or url and this alert shows "undefined" ...
alert(object);
while this alert doesn't work at all
alert(object.id);
in the end, i read this page chrome.tabs and i was shocked when i read this line
getCurrent
chrome.tabs.getCurrent(function callback)
Gets the tab that this script call is being made from. May be undefined if called from a non-tab context (for example: a background page or popup view).
so i don't think that there is a solution of getting the current opened tab from chrome extension...
I believe that you need to use getSelected instead
<html>
<head>
<script>
chrome.tabs.getSelected(null, function(tab) {
var tabId = tab.id;
var tabUrl = tab.url;
alert(tabUrl);
});
</script>
</head>
the final code was like this, and it worked just fine.. :
var tabUrl;
chrome.browserAction.onClicked.addListener(function(activeTab) {
var x=activeTab.url;
var newURL = "https://www.google.com";
if (x!= newURL) {
//to open a page in a new tab
chrome.tabs.create({url: newURL,"selected":true});
//to open the page with the current tab
chrome.tabs.update(activeTab.id, {url:newURL});
}
});
The current accepted answer is out of date.
According to MDN, tabs.getSelected() is depricated
Use this instead:
tabs.query({active: true})
Ensure to set the correct permissions in manifest.json to access tab information:
"permissions": [
"tabs",
"http://*/*"
],
After that, you can determine the URL by using
chrome.tabs.getSelected(null, function (tab) {
alert(tab.url);
});

How to implement Chrome extension 's chrome.tabs.sendMessage API in Firefox addon

I'm working on a Firefox addon development with Addon-Builder. I have no idea about how to implement Chrome extension 's chrome.tabs.sendMessage API in Firefox addon. The code is like this (the code is in the background.js, something like main.js in the Firefox addon):
function sendMessageToTabs(message, callbackFunc){
chrome.tabs.query({}, function(tabsArray){
for(var i=0; i<tabsArray.length; i++){
//console.log("Tab id: "+tabsArray[i].id);
chrome.tabs.sendMessage(tabsArray[i].id,message,callbackFunc);
}
});
}
So, How can I achieve this?
In add-ons build using the Add-on SDK, content scripts are managed by main.js. There's no built-in way to access all of your add-on's content scripts. To send a message to all tabs, you need to manually keep track of the content scripts.
One-way messages are easily implemented by the existing APIs. Callbacks are not built-in, though.
My browser-action SDK library contains a module called "messaging", which implements the Chrome messaging API. In the following example, the content script and the main script use an object called "extension". This object exposes the onMessage and sendMessage methods, modelled after the Chrome extension messaging APIs.
The following example adds a content script to every page on Stack Overflow, and upon click, the titles of the tabs are logged to the console (the one opened using Ctrl + Shift + J).
lib/main.js
// https://github.com/Rob--W/browser-action-jplib/blob/master/lib/messaging.js
const { createMessageChannel, messageContentScriptFile } = require('messaging');
const { PageMod } = require('sdk/page-mod');
const { data } = require('sdk/self');
// Adds the message API to every page within the add-on
var ports = [];
var pagemod = PageMod({
include: ['http://stackoverflow.com/*'],
contentScriptWhen: 'start',
contentScriptFile: [messageContentScriptFile, data.url('contentscript.js')],
contentScriptOptions: {
channelName: 'whatever you want',
endAtPage: false
},
onAttach: function(worker) {
var extension = createMessageChannel(pagemod.contentScriptOptions, worker.port);
ports.push(extension);
worker.on('detach', function() {
// Remove port from list of workers when the content script is deactivated.
var index = ports.indexOf(extension);
if (index !== -1) ports.splice(index, 1);
});
}
});
function sendMessageToTabs(message, callbackFunc) {
for (var i=0; i<ports.length; i++) {
ports[i].sendMessage(message, callbackFunc);
}
}
// Since we've included the browser-action module, we can use it in the demo
var badge = require('browserAction').BrowserAction({
default_title: 'Click to send a message to all tabs on Stack Overflow'
});
badge.onClicked.addListener(function() {
sendMessageToTabs('gimme title', function(response) {
// Use console.error to make sure that the log is visible in the console.
console.error(response);
});
});
For the record, the interesting part of main.js is inside the onAttach event.
data/contentscript.js
extension.onMessage.addListener(function(message, sender, sendResponse) {
if (message === 'gimme title') {
sendResponse(document.title);
}
});

Resources