在Google Chrome应用网页视图的新标签页中打开链接

时间:2015-07-03 10:01:03

标签: google-chrome webview google-chrome-app google-chrome-webview

我有一个带有webview控件的Google Chrome应用。 webview中的某些链接旨在在新标签页(target="_blank")中打开。但是,单击这些链接不会执行任何操作,右键单击它们不会打开上下文菜单来打开/复制链接。我该如何启用此类链接?

1 个答案:

答案 0 :(得分:1)

这是我迄今为止最好的:

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);