Reputation: 19611
I have a Google Chrome App with a webview control. Some of the links in the webview are meant to open in a new tab (target="_blank"
). However, clicking those links doesn't do anything, and right-clicking on them doesn't open a context menu to open/copy the link. How can I enable such links?
Upvotes: 1
Views: 831
Reputation: 19611
This is the best I've come up with so far:
var webview = null;
function isSafeUrl(url) {
// You may want to perform a more rigorous check.
// There's a technique that creates an <a> to parse the URI, but that seems
// like a security risk.
return !!url.match(/^(?:ftp|https?):\/\//i);
}
function onNewWindow(event) {
if (!isSafeUrl(event.targetUrl)) {
console.warn('Blocking unsafe URL: ' + event.targetUrl);
event.window.discard();
return;
}
var newWindow = null, features = '';
switch (event.windowOpenDisposition) {
case 'ignore':
// Not sure what this is used by. Default enum value, maybe.
console.debug('Ignoring new window request');
return;
case 'save_to_disk':
// Ctrl + S, maybe? Not sure how to reproduce that.
console.log('save_to_disk is not implemented');
return;
case 'current_tab':
webview.src = event.targetUrl;
break;
case 'new_background_tab':
case 'new_foreground_tab':
newWindow = open(event.targetUrl, '_blank');
if (event.windowOpenDisposition != 'new_background_tab') {
newWindow.focus();
}
break;
case 'new_window':
case 'new_popup':
if (event.initialWidth && event.initialHeight) {
features = 'width=' + event.initialWidth + ',height=' + event.initialHeight;
}
newWindow = open(event.targetUrl, '_blank', features);
newWindow.focus();
break;
}
}
function onDomReady() {
webview = document.getElementById('webview');
webview.addEventListener('newwindow', onNewWindow);
}
document.addEventListener('DOMContentLoaded', onDomReady);
Upvotes: 1