在新标签页中打开新网页后,如何在书签中获取JavaScript代码? [英] How do I get JavaScript code in a bookmarklet to execute after I open a new webpage in a new tab?

查看:129
本文介绍了在新标签页中打开新网页后,如何在书签中获取JavaScript代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在试图弄清楚如何让我的书签以我想要的方式工作。这是我的问题。我有一个JS书签,它抓取一个安全的网页,并使用这些DOM元素来运行我的代码。

I'm trying to figure out how I can get my bookmarklet to work the way I want it to. Here's my issue. I have a JS bookmarklet that scrapes a secure webpage and uses those DOM elements to run my code.

我的问题是,当我点击我的书签时,它会在新标签页中打开新页面并立即开始运行我打算为新打开的页面运行的代码。例如,当我单击书签时,我用于存储用户输入的提示窗口立即在我当前页面上运行。我的预期行为是首先在新选项卡中打开新页面,加载页面,然后使用该新页面的DOM元素运行提示和其余代码。我正在使用安全网页,所以我将使用谷歌主页作为示例。

My issue is, when I click on my bookmarklet, it opens the new page in a new tab and immediately starts running the code I intend to run for the newly opened page. For example, a prompt window that I'm using to store user input runs immediately on the current page I'm on when I click the bookmarklet. My intended behavior is to first open the new page in a new tab, load the page, then run the prompt and the rest of the code using the DOM elements of that new page. I'm using a secure webpage so I'll use google homepage for an example.

以下是一个示例:

javascript: (function() {

function OpenInNewTab(url){
  var win = window.open(url);
  win.focus();
}
OpenInNewTab("https://www.google.com/?gws_rd=ssl");

var prmt = prompt("Enter a date:");
window.onload = prmt;

})();

最终,我希望代码可以做3件事。

Ultimately, I'd like the code to do 3 things.


  1. 从任意页面点击新标签页面时打开新窗口

  2. 进入新标签页并加载页面

  3. 然后在新打开的页面上运行我的代码

我希望我已经解释得很好!一如既往,非常感谢任何信息。谢谢!

I hope I have explained myself well! As always, any information is greatly appreciated. thanks!

推荐答案

您需要参考正确的窗口。在要单击的每个单独页面上使用相同的 id 最简单,然后通过 src < script> 标记的属性。

You need to refer to the correct window. It would be easiest to have the same id on each separate page you want to click on, then include the following script through the src attribute of the <script> tag.

function openInNewTab(clickElement, url){
  clickElement.onclick = function(){
    var win = open(url);
    win.focus();
    var prm = win.prompt('Enter a Date: ', 'March 11, 2015');
    if(prm){
      console.log('The Date You Entered was: '+prm);
    }
    return win;
  }
}
var pre = onload; // previous onload
onload = function(){ // window is implicit
  if(pre)pre();
  var newWin = openInNewTab(document.getElementById('click_input_id'), 'https://www.google.com')
}

这篇关于在新标签页中打开新网页后,如何在书签中获取JavaScript代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆