Này người xa lạ!

Còn chờ gì nữa mà không mau đăng nhập hoặc đăng ký để cùng tham gia thảo luận với cộng đồng!

jquery works in the console while not when saved and run on page load.

đã sửa January 1 trong Phát triển Firefox

I am running a greasemonkey javascript. jquery works fine when I copy and paste into the console. jquery does not work when I use greasemonkey to run the javascript when the page loads. I am using jquery, $(). jquery is coming back as unfound. I tried to define $, but didn't help. See comment in code. I trimmed the js down. I'm runnning with this page:
https://discussions.apple.com/thread/250050666

macos 10.10.5
waterfox 56.2.6 a clone of Firefox. Supports legacy Firefox plugins.
greasemonkey 3.17

my script:
It delays for 10 seconds. Tries three different query commands. For some reason, $("body"); is not being found. While document.querySelector("body"); and document.querySelectorAll("body"); are being found. I defined $() as shown in a comment, but this didn't change the result. If I copy and run the script from the console $() works.

How do I get jquery to work?

the results.

`
==++> setup. Mon Dec 31 2018 18:48:17 GMT-0500 (EST)

adding locationChangeButton event listner

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at
https://www.apple.com/search-services/suggestions/. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing). (unknown)

Use of Mutation Events is deprecated. Use MutationObserver instead. index.js:8:30800

======> Lets begin. delay completed <======

---> locationChangeButtonHandler is observed.

document.readyState is complete

Trying querySelectorAll

using querySelectorAll

Trying jquery

No jquery. Error is** "$ is not defined" **

Trying querySelector

using querySelector

In stopWatchDogButton 5

watchdog is inactive : 5

end of locationChangeButtonHandler

stopping. watchdog1 is 5

In stopWatchDogButton 5

watchdog is inactive : 5`

`

// ==UserScript==
// @name        ASCClickerV2
// @namespace   bubo-bubo/gmscripts
// @description Show all posts in a thread.
// @include     /https://discussions\.apple\.com/+thread/+.*/
// @version     25Dec2018
// @grant       none
// ==/UserScript==


// Uses Hiroto's event handler design. 
// var $ = unsafeWindow.jQuery;
var watchdog1;
var watchInterval = 1000*10;       // [ms] Waiting for the user to change page
var debug = 2;                     // 0 -- no debug
                                   // 1 -- normal debug
                                   // 2 -- intense debug

var aDate = new Date();
console.log ("==++> setup. " + aDate);

// register event listeners
// nothing like starting at the end ;-)

 window.addEventListener('unload', function(e) {
          if (debug) console.log('unloading.');
          stopWatchDogButton(watchdog1);
          window.removeEventListener('locationChangeButton',
                                      locationChangeButtonHandler, 
                                      true);
          // remove anonymous unload. [ Thus unload ]
          // remove myself!
          window.removeEventListener(e.type, 
                                     arguments.callee, 
                                     true);
        }, true );

 console.log('adding locationChangeButton event listner');
 window.addEventListener('locationChangeButton', 
                         locationChangeButtonHandler, 
                         true);

// delay until the page is loaded. 
 watchdog1 = setInterval( function() 
        {
              console.log('======> Lets begin. delay completed  <======');
              window.dispatchEvent(new Event('locationChangeButton'));
              console.log("stopping. watchdog1 is " + watchdog1)
              stopWatchDogButton(watchdog1);           
         },
         watchInterval ); // end of setting watch dog #1

// last set value is returned as return code.
var done;
done = 0;

// -----------------------------------------------------------------------------
function locationChangeButtonHandler(e) {
         var sectionSpin;
         console.log('---> locationChangeButtonHandler is observed. ');  

         console.log(" document.readyState is " + document.readyState);

         try{
          console.log ("Trying  querySelectorAll");
                       // was body div.helpful-all-toggler div.drop-down-header-wrapper
          sectionSpin = document.querySelectorAll("body");
          console.log ("using querySelectorAll");
         }             
         catch(err)
         {
          console.log ("No querySelectorAll.  Error is \""+ err.message + "\"" )
         }

         try{
          console.log ("Trying jquery");
          sectionSpin = $("body");
          console.log ("using jquery");
         }             
         catch(err)
         {
          console.log ("No jquery.  Error is \""+ err.message + "\"" )
         }

         try{
          console.log ("Trying  querySelector");
                       // was body div.helpful-all-toggler div.drop-down-header-wrapper
          sectionSpin  = document.querySelector("body");
          console.log ("using querySelector");
         }             
         catch(err)
         {
          console.log ("No querySelector.  Error is \""+ err.message + "\"" )
         }
         stopWatchDogButton(watchdog1);
         console.log("end of locationChangeButtonHandler");
        } // end of locationChangeButtonHandler



/* --------------------------------------------------------------------- */
/* print out objects:
      https://stackoverflow.com/questions/957537/how-can-i-display-a-javascript-object
      https://code-maven.com/logging-javascript-objects
*/
function spew (inputObj) {
  if (debug) {
    console.log ("typeof inputObj is " + typeof inputObj)
    console.log ("inputObj is: ")
    console.log ( inputObj)
  }
  if (debug>=2) {
    //this will show object gandalf IN ALL BROWSERS!
    console.log(JSON.stringify(inputObj));
    //this will show object gandalf IN ALL BROWSERS! with beautiful indent
    console.log(JSON.stringify(inputObj, null, 4));
    console.log(Object.keys(inputObj));
    console.log(Object.values(inputObj));

    //There is also this new option if you're using ECMAScript 2016 or newer:
    try {
      Object.keys(inputObj).forEach(e => console.log(`key=${e}  value=${inputObj[e]}`));
    }
    catch (err) {
      console.log (" You must need ECMAScript 2016 or newer \""+ err.message + "\"" )
    } 
    // alert (inputObj) 
    //var object = this.window;
    //console.log(object,'this is window object');
  } // end of if debug
} // end of function spew


/* --------------------------------------------------------------------- */

function stopWatchDogButton(dog) {
    console.log("In stopWatchDogButton " + dog)
    clearInterval(dog);
    console.log('watchdog is inactive : ' + dog);
}

`

Bình luận

  • there is security limit in greasemonkey 4 so you cannot access variable but only the element in the document.As solution,you can @require a jquery on the script head so it can use jquery of itself instead of document's variable,or stringify the script and inject it into the document so it can use anything in the document.In another way just use Tampermonkey or Violentmonkey instead of greasemonkey 4 and the code will work without change

  • đã sửa January 2 [?]

    Thanks. This is the first time I've posted here. Is there something to click or mark that indicates this post was helpful or solved my issue?

Đăng nhập hoặc Đăng ký để gửi bình luận.