Why doesn't this code get the URL from Safari? - javascript

I am creating a safari extension. When the user right-clicks on a link in safari, it should bring up the context menu. When the user clicks on "Get URL", it should open the clicked on url in a new window. I can't figure out how to get the url! It always opens "not found" instead.
injected.js :
document.addEventListener('contextmenu', handleContextMenu, false);
function handleContextMenu(event)
{
var target = event.target;
while(target != null && target.nodeType == Node.ELEMENT_NODE && target.nodeName.toLowerCase() != "a")
{
target = target.parentNode;
}
if(target.href)
{
safari.self.tab.setContextMenuEventUserInfo(event, target.href);
}
else
{
var foo = "href not found";
safari.self.tab.setContextMenuEventUserInfo(event, foo);
}
}
Global.html:
<!DOCTYPE HTML>
<script>
var lastUrl;
safari.application.addEventListener("contextmenu",handleContextMenu,false);
safari.application.addEventListener('command', handleCommand, false);
function handleContextMenu(event)
{
var query = event.userInfo;
lastUrl = query;
event.contextMenu.appendContextMenuItem("getUrl", "Get URL");
}
function handleCommand(event)
{
if(event.command === 'getUrl')
{
if (lastUrl)
{
safari.application.openBrowserWindow().activeTab.url = lastUrl;
}
else
{
safari.application.openBrowserWindow().activeTab.url = "not found";
}
}
}
</script>
How do I get the url? It always opens "not found" instead.

Why not just have var last url = event.userInfo in the handleCommand function? The userInfo should be defined at that point, and it should be more predictable that trying to set the value on the contextmenu event.

I don't understand why your code is not working, but there are a couple of things you might want to change anyway.
First, in the injected content script, if there's no target.href, don't bother calling safari.self.tab.setContextMenuEventUserInfo.
Second, in the global script, change your handleContextMenu function as follows:
function handleContextMenu(event) {
if (event.userInfo) {
event.contextMenu.appendContextMenuItem("getUrl", "Get URL");
}
}
That way, if the user didn't right-click a link, the context menu item won't be inserted.
Third, as Matt said, you don't need the lastUrl global variable, unless it serves some other purpose. You can refer to event.userInfo directly in handleCommand. And you don't need to check whether it's empty, because the context menu will only be inserted by handleContextMenu if it's not.
function handleCommand(event) {
if (event.command === 'getUrl') {
safari.application.openBrowserWindow().activeTab.url = event.userInfo;
}
}
Hope this helps.

Related

Displaying Docs w/n a View Panel via a Dialog

I have an XPages app, whereas I have an XPage that contains a viewpanel and two Custom Controls...both custom controls are dialogs that are used to entered information. All this works perfectly. However, what I am interested in is: how do I get a handle on selected/clicked document and display it via a dialog. I am somewhat familiar for with the "var" variable w/n the viewpanel properties, but am not sure this is the right approach, or even how to finish it. Can someone advise as to how to accomplish this, or even if I should go about it differently? Thanks in advance.
onClick - vwColumn & pageURL event:
var dataRes;
if (rowData.isCategory()) {
return "";
}
var href = facesContext.getExternalContext().getRequest().getContextPath();
try {
var doc = rowData.getDocument();
if (doc != null) {
var docID = doc.getUniversalID();
var formType = rowData.getColumnValue("Form")
if(formType == "Memo") {
dataRes = href + "/memoXP.xsp?documentId=" + docID + "&action=openDocument";
} else {
dataRes = href + "/";
}
}
} catch (e) {
#WarningMessage(e)
}
if (doc != null) {
doc.recyle();
}
return dataRes;

How to get Chrome to throw exception when changing url if it fails

I have a reference to a new window opened with js
var theNewTab="";
theNewTab = window.open(theURL, 'winRef');
then I change the url in the as the user clicks on another link in the parent window using
theNewTab.location.href = targetLink;
theNewTab.focus();
The problem i'm having with chrome that id doesn't throw exception if the the window doesn't exist anymore "closed" unlink FF & IE which im using to open the window again.
try {
theNewTab.location.href = targetLink;
theNewTab.focus();
}catch(err) {
theNewTab = window.open(theURL, 'winRef');
theNewTab.focus();
}
PS: I tried to use "window.open" every time but if the window already open, id does not reload the page or it does but it doesn't re-execute the script I have in document ready I think.
I'm not sure what you need.
<script type="text/javascript">
var theNewTab = null;
function openNewTab(theURL) {
if (theNewTab == null || theNewTab.closed == true) {
theNewTab = window.open(theURL);
} else {
theNewTab.location.href = theURL;
}
theNewTab.focus();
};
// use the function when you need it
$('a').click(function() {
openNewTab($(this).attr('href'));
});
</script>
Is this example helpful for you?

Navigate stop only when going to another website

I am using following code to trigger the are you sure leaving website alert but for some reason its not recognising my if else condition in it and only works if I only put return true in window.onbeforeunload = function() { return true } . Is there a way I can trigger this alert only when user is navigating away from my website cause at the moment without if else condition its asking if user tries to navigate in the same website as well?
window.onbeforeunload = function() {
var location = window.document.activeElement.href;
if (typeof location != 'undefined')
{
console.log(location);
} else { reutn true; }
};
You can set a flag and toggle that flagged based on host of links that are clicked
var host = location.hostname,
allowNavigate = false;
window.onbeforeunload = function() {
if (!allowNavigate) {
return 'Message string';// not what actually gets displayed in most browsers these days
}
//don't return anything
return;
};
window.onload = function() {
document.querySelectorAll('a').forEach(function(a) {
a.addEventListener('click', function(e) {
allowNavigate = this.hostname === host;
});
});
};
The hostname on this page for example is "stackoverflow.com"
DEMO
You can add the "window.onbeforeunload" dynamically for the links you want to see the prompt message
and remove the "window.onbeforeunload" for the links you don't want prompt
<a onClick="a(true)" href="https://www.w3schools.com">Click here to get promt before navigate</a>
<br>
<a onClick="a(false)" href="https://jsfiddle.net/">Click here to navigate without promt </a>
<script>
function a(showPrompt){
window.onbeforeunload = showPrompt ? function(e) {return '';}: null;
}
</script>
https://jsfiddle.net/vqsnmamy/1/

Troubleshoot of beforeunload confirm call

My Code:
//hold window open on form change
window.onbeforeunload = function(e) {
if(formChanges > 0) {
if(formData != initFormData) {
if(confirm('here')) {
e.preventDefault();
}
else {
e = null;
}
}
else {
e = null;
}
}
else {
e = null;
}
};
The three vars (formChanges, formData, and initFormData) are all being filled correctly, and little tests have shown that they are being read correctly within the function. The problem is that the page unloads nomatter what, and no confirmation dialog ever appears.
The console log flashes for a moment before being unloaded (I can't seem to write it's contents to file) and I can see the message Blocked confirm 'here' during beforeunload, but it's gone before I can access it. Any help is appreciated!
WHen using onbeforeunload you have to return a string, like so:
window.onbeforeunload = function(e) {
return 'Dialog text here.';
};
source: https://developer.mozilla.org/en-US/docs/Web/API/Window.onbeforeunload

popup window only 'popping up' once in safari

I have a JavaScript fired popup window, it's created when hitting the onclick event of a tag:
top.popUp('/bus/popup.asp', '', 'height=457px,width=525px,status=no,scrollbars=no,resizable=yes,location=no,menubar=no,toolbar=no');return false;">
function popUp(url, winName, params, win)
{
var winExists = false;
if (win.handler)
{
if (!(win.handler == "" || win.handler.closed || win.handler.name == undefined))
{
winExists = true;
}
}
if (!winExists)
{
win.handler = window.open(url, winName, params)
}
try
{
win.handler.focus();
}
catch (e)
{
}
return false;
}
I also found these two funky little functions in the main file, fired when the popup window gets unloaded:
// Hack for onUnload and onBeforeUnload
onBeforeUnloadHappened = false;
closeDirectly = false;
function onBeforeUnloadHandler()
{
if (!closeDirectly)
{
openerUnhilightSaveLink();
onBeforeUnloadHappened = true;
}
}
function onUnloadHandler()
{
if (!closeDirectly)
{
if (!onBeforeUnloadHappened)
{
openerUnhilightSaveLink();
}
else
{
onBeforeUnloadHappened = false;
}
}
}
The problem is that in Safari, the window will only popup once, each subsequent click on the link gets you nada, zilch, nothing... how do I correct this?
I did find a couple of articles, Google is my friend, online and they suggested that I add this.close(), which I did to the unload event but it doesn't seem to have solved the problem.
The other thing I find odd is that the onUnloadHandler() doesn't actually happen each time the page is unloaded! Shouldn't this be called each time by the page itself irrespective of what else has happened?!
Thanks
It's my opinion that your popup code isn't written properly. This works in Safari, as I just tested it out. This is what I've done.
// Create a global popup object as you should rarely ever
// have more than one popup open at a time.
window.popUpObj = null;
// The function to call the popup.
function popUp(url, winName, params)
{
// If the window has not been defined or if it has been closes open it.
// Since we defined window.popUpObj to be null we'll expect only 2 conditions.
if(window.popUpObj == null || window.popUpObj.closed)
{
window.popUpObj = window.open(url, winName, params);
}
// Get window focus
window.popUpObj.focus();
// Return false.
// we do this so that when we call it we don't need a ; to return false afterwards
// we just add return before the function call. It's a bit more elegant.
return false;
}
You can call it like this. You should by the way always populate the 2nd parameter with something.
Link
Here's a working HTML doc.
<html>
<head>
<script type="text/javascript">
window.popUpObj = null;
function popUp(url, winName, params)
{
// If the window has not been defined or if it has been closes open it.
if(window.popUpObj == null || window.popUpObj.closed || window.popUpObj.name == undefined)
{
window.popUpObj = window.open(url, winName, params);
}
// Get window focus
window.popUpObj.focus();
// Return false.
return false;
}
</script>
</head>
<body>
Link
close
</body>
</html>

Categories