简体   繁体   中英

How do I get JavaScript code in a bookmarklet to execute after I open a new webpage in a new tab?

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 web page and uses those DOM elements to run my code.

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.

Here's 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;

})();

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

  1. Open the new window in a new tab when clicking on it from any page
  2. Be in that new tab and load the page
  3. Then run my code on that newly opened page

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

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')
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM